#!/bin/bash
# areaclick - root (desktop) areas/edges on click actions for Openbox

CFG_FILE="$HOME/.config/areaclick.conf"

makeconf() {
cat <<EOF > ${CFG_FILE}
# Sidearea width/height in pixels (set to 0 to disable side actions)
sidearea=100

# Commands 
# Center area (or whole desktop if sidearea = 0)
cmd_center=show_desktop

# Sidearea commands:
cmd_topleft=show_desktop
cmd_top="jgdesktops -s"
cmd_topright="mb-music -s"

cmd_left="mb-jgtools places 2>/dev/null"
cmd_right="mb-jgtools right 2>/dev/null"

cmd_bottomleft="skippy-xd --expose"
cmd_bottom="skippy-xd --paging"
cmd_bottomright="mb-jgtools mblogout"

# Editor (for areaclick editconf command)
editor=geany
EOF
}


if [ ! -f ${CFG_FILE} ]; then
makeconf
fi

# read config variables from file
source <(grep = $CFG_FILE)



topleft() {
if [ -n "$cmd_topleft" ];then
	bash <<< "$cmd_topleft"
else
	left
fi
}

left(){
if [ -n "$cmd_left" ];then
	bash <<< "$cmd_left"
else
	center
fi
}

bottomleft() {
if [ -n "$cmd_bottomleft" ];then
	bash <<< "$cmd_bottomleft"
else
	left
fi	
}

topright() {
if [ -n "$cmd_topright" ];then
	bash <<< "$cmd_topright"
else
	right
fi
}

right(){
if [ -n "$cmd_right" ];then
	bash <<< "$cmd_right"
else
	center
fi
}

bottomright() {
if [ -n "$cmd_bottomright" ];then
	bash <<< "$cmd_bottomright"
else
	right
fi	
}

top(){
if [ -n "$cmd_top" ];then
	bash <<< "$cmd_top"
else
	center
fi
}

center(){
bash <<< "$cmd_center"	
}

bottom() {
if [ -n "$cmd_bottom" ];then
	bash <<< "$cmd_bottom"
else
	center
fi	
}

_leftside(){
if [ $Y -lt $((Y_OFF+sidearea)) ];then #topleft
topleft
elif [ $Y -gt $((Y_OFF+HEIGHT-sidearea)) ];then #bottomleft
bottomleft	
else
left
fi
}
_rightside () {
if [ $Y -lt $((Y_OFF+sidearea)) ];then #topright
topright
elif [ $Y -gt $((Y_OFF+HEIGHT-sidearea)) ];then #bottomright
bottomright	
else
right
fi
}

_middle () {
if [ $Y -lt $((Y_OFF+sidearea)) ];then #top
top
elif [ $Y -gt $((Y_OFF+HEIGHT-sidearea)) ];then #bottom
bottom	
else
center
fi
}

_main() {
# Get mouse location
eval $(xdotool getmouselocation --shell)

# get monitor width,height and x,y-offset on current monitor (the one where pointer is)
while read -r line; do
    info=$(echo $line | awk '{print $3}')
    if [[ $info == primary ]]; then
        info=$(echo $line | awk '{print $4}')
    fi
    read WIDTH HEIGHT X_OFF Y_OFF <<< $(echo $info | awk -F[x+] '{print $1, $2, $3, $4}')
    if (( X >= X_OFF && X <= WIDTH + X_OFF )); then
        break
    fi
done < <(xrandr | grep " connected")	

if [ $X -lt $((X_OFF+sidearea)) ];then
_leftside
elif [ $X -gt $((X_OFF+WIDTH-sidearea)) ];then
_rightside
else
_middle
fi
}
editconf(){
 $editor $CFG_FILE	
}
reset(){
makeconf
}
area() {
mb-setvar sidearea=${1} $CFG_FILE	
}

case "$1" in
	topleft) topleft;;
	top) top;;
	topright) topright;;
	left) left;;
	center) center;;
	right) right;;
	bottomleft) bottomleft;;
	bottom) bottom;;
	bottomright) bottomright;;
	editconf) geany $CFG_FILE;;
	reset) reset;;
	area) area "$2";;
	*) _main;;
esac
