#!/bin/bash

# t2-cortile - tint2 executor to assist with cortile tiling manager
# quick and dirty currently for demo purposes only

CORTILE_CFG="$HOME/.config/cortile/config.toml"
IMG_DIR="$HOME/.config/cortile/tint2-cortile"


sendkey(){
	read KEYS<<< $(grep "^${1}.*=.*$" $CORTILE_CFG | cut -d'"' -f2)
	XDOTOOL_KEYS=${KEYS//-/+}
	XDOTOOL_KEYS=${XDOTOOL_KEYS/Control/ctrl}
	XDOTOOL_KEYS=${XDOTOOL_KEYS/Super_L/super}
	XDOTOOL_KEYS=${XDOTOOL_KEYS/Space/space}
	XDOTOOL_KEYS=${XDOTOOL_KEYS/KP_4/KP_Left}
	XDOTOOL_KEYS=${XDOTOOL_KEYS/KP_6/KP_Right}
	XDOTOOL_KEYS=${XDOTOOL_KEYS/KP_8/KP_Up}
	XDOTOOL_KEYS=${XDOTOOL_KEYS/KP_2/KP_Down}
	#notify-send.sh "$1" "$KEYS \n$XDOTOOL_KEYS"
	xdotool key ${XDOTOOL_KEYS}
}

is_tiled(){
	grep workspace-$(xdotool get_desktop) /tmp/cortile.log |tail -n 1 |grep Tile >/dev/null
}
is_fullscreen(){
	grep workspace-$(xdotool get_desktop) /tmp/cortile.log |tail -n 1 |grep fullscreen >/dev/null
}
get_current_layout(){
	layout=$(grep workspace-$(xdotool get_desktop) /tmp/cortile.log |tail -n 1| cut -d' ' -f6)
	case "$layout" in
	vertical-right) echo ${IMG_DIR}/vertical-right.png;;
	vertical-left) echo ${IMG_DIR}/vertical-left.png;;
	horizontal-top) echo ${IMG_DIR}/horizontal-top.png;;
	horizontal-bottom) echo ${IMG_DIR}/horizontal-bottom.png;;
	fullscreen) echo ${IMG_DIR}/fullscreen.png;;
	esac
}
main(){
if pgrep -x cortile >/dev/null ;then
if is_tiled ;then
	get_current_layout
	else
	echo "${IMG_DIR}/untiled.png"
	fi
fi
}

left(){
if is_tiled ;then
	if is_fullscreen ;then
	sendkey untile
	else
	sendkey layout_cycle
	fi
else
	sendkey tile
	sendkey layout_vertical_left
fi
}
middle(){
if is_tiled ;then
	sendkey untile
else
	sendkey tile
fi
}
right(){
if is_tiled ;then
	sendkey untile
else
	sendkey tile
fi
}
up(){
if is_tiled; then
	if is_fullscreen ;then
		sendkey window_previous
	else
		sendkey proportion_increase
	fi
else
xdotool set_desktop --relative 1
fi
}
down(){	
if is_tiled; then
	if is_fullscreen ;then
		sendkey window_next
	else	
		sendkey proportion_decrease
	fi
else
xdotool set_desktop --relative -- -1
fi	
}

case "$1" in
	left)left;;
	right)right;;
	middle)middle;;
	up)up;;
	down)down;;
	*)main;;
esac
