#!/bin/bash
# helper script for editing Openbox rc.xml config file

nspace="http://openbox.org/3.4/rc"
rcxml="$HOME/.config/openbox/rc.xml"
reconf=0

sel(){
xml sel -N a="$nspace" -t -v ${1} "$rcxml"
}

set(){
xml ed -L -N a="$nspace" -u ${1} -v ${2} "$rcxml"
reconf=1
}
setonly(){
xml ed -L -N a="$nspace" -u ${1} -v ${2} "$rcxml"
}

switch_desk(){
case "$1" in
	on)
	set '/a:openbox_config/a:mouse/a:context[@name="Root"]/a:mousebind[@action="Click"][@button="Up"]/a:action/a:to' previous
	set '/a:openbox_config/a:mouse/a:context[@name="Root"]/a:mousebind[@action="Click"][@button="Down"]/a:action/a:to' next
	;;
	off)
	set '/a:openbox_config/a:mouse/a:context[@name="Root"]/a:mousebind[@action="Click"][@button="Up"]/a:action/a:to' none
	set '/a:openbox_config/a:mouse/a:context[@name="Root"]/a:mousebind[@action="Click"][@button="Down"]/a:action/a:to' none
	;;
esac

}

show_desk(){
case "$1" in
	on)
	set '/a:openbox_config/a:mouse/a:context[@name="Root"]/a:mousebind[@action="Press"][@button="Left"]/a:action/@name' ToggleShowDesktop
	;;
	off)
	set '/a:openbox_config/a:mouse/a:context[@name="Root"]/a:mousebind[@action="Press"][@button="Left"]/a:action/@name' none
	;;
esac
}
focus_follow_mouse(){
case "$1" in
	on)
	set '/a:openbox_config/a:focus/a:followMouse' yes
	set '/a:openbox_config/a:focus/a:raiseOnFocus' yes
	;;
	off)
	set '/a:openbox_config/a:focus/a:followMouse' no
	set '/a:openbox_config/a:focus/a:raiseOnFocus' no
	;;
esac
}

desktops() {
	set '/a:openbox_config/a:desktops/a:number' ${1}
	wmctrl -n ${1}
}
margin() {
case "$1" in
	top|bottom|left|right)
	setonly "/a:openbox_config/a:margins/a:${1}" ${2}
	;;
	all)
	setonly "/a:openbox_config/a:margins/a:top" ${2}
	setonly "/a:openbox_config/a:margins/a:bottom" ${2}
	setonly "/a:openbox_config/a:margins/a:left" ${2}
	setonly "/a:openbox_config/a:margins/a:right" ${2}
	;;
esac
reconf=1
}

case "$1" in
sel)sel "$2";;
set)set "$2" "$3";;
switch_desk)switch_desk "$2";;
show_desk)show_desk "$2";;
focus_follow_mouse)focus_follow_mouse "$2";;
desktops)desktops "$2";;
margin)margin "$2" "$3";;
esac

[[ "$reconf" = "1" ]] && openbox --reconfigure
