#!/bin/sh -x

# Get class of a wid
get_class() {
    set -x
    [ ! -z "$1" ] \
        && xprop -id "$1" -notype WM_CLASS | cut -d'"' -f2
}

get_pid() {
    set -x
    [ ! -z "$1" ] \
        && xprop -id "$1" -notype _NET_WM_PID | cut -d'=' -f2
}

get_parentpid() {
    ps -o "ppid=" -f -p $1
}

get_command() {
    ps -o comm= -p $1
}


swallow() {
    set -x
    addedtodesktop=$2
    lasttermdesktop=$(bspc query -D -n last)

    swallowerid=$1
    swallowingid=$(bspc query -N -n last)

    if [ "$addedtodesktop" == "$lasttermdesktop" ]; then
            grep "^$(get_class "$swallowerid")$" ~/.config/bspwm/swallow || return
            grep "^$(get_class "$swallowingid")$" ~/.config/bspwm/terminals || return
            echo "$swallowerid $swallowingid" >> /tmp/swallowids
            bspc node "$swallowingid" --flag hidden=on
    fi
}

spit() {
        spitterid=$1
        spitterdesktop=$2

        grep "^$spitterid" /tmp/swallowids \
            || return

        spittingid=$(grep "^$spitterid" /tmp/swallowids | head -n1 | awk '{ print $2 }')

        bspc node "$spittingid" --flag hidden=off

        termdesktop=$(bspc query -D -n "$spittingid")

        [ "$termdesktop" == "$spitterdesktop" ] \
            || bspc node "$spittingid" -d "$spitterdesktop"

        bspc node "$spittingid" -f

        sed -i "/^$spitterid/d" /tmp/swallowids
}

bspc subscribe node_add node_remove | while read -r event
do
        case $(echo "$event" | awk '{ print $1 }') in
                node_add)
                        swallow $(echo "$event" | awk '{ print $5 " " $3}')
                        ;;
                node_remove)
                        spit $(echo "$event" | awk '{ print $4 " " $3}')
                        ;;
        esac
done