#!/usr/bin/env bash

# Script: bspc-swap
# Author: Henrik Lissner
# Usage:
#   bspc-swap [-m] (west|south|north|east)
#   bspc-swap south
#   bspc-swap -m west
#
# Swaps current window with the window in a direction. If -m is set, move window
# to the next monitor in that direction.
#
# The behavior of the base 'bspc node -s' is odd when crossing screens. It will
# swaps with the last selected window on that screen, rather than the window on
# the connecting edge, which is unintuitive.

set -e

leap=
if [[ $1 == -m ]]; then
    leap=1
    dir=$2
else
    dir=$1
fi

case $dir in west|south|north|east) ;;
    *) >&2 echo "Not a valid direction: $dir"
        exit 1
esac

if [[ -n $leap ]]; then
    # move window to monitor in direction
    old_id=$(bspc query -N -n focused)
    if [[ $(bspc query -M -m "$dir") ]]; then
        bspc node -m "$dir"
        bspc node -f "$old_id"
    fi
else
    # move window in direction
    old_id=$(bspc query -N -n focused)
    if bspc node -s "$dir.local"; then
        bspc node -f "$old_id"
    elif [[ -n $(bspc query -M -m "$dir") ]]; then
        bspc node -m "$dir"
        bspc node -f "$old_id"
    fi
fi
