#!/bin/bash
# www.xeron.cc
# Version 4! Major rewrites to the entire script.
#
# Please make sure the theme name you have in your RC file is the same as one
# of the ones in your $THEME_PATH. Otherwise the script has no way of finding
# the correct line to change in your rc.xml. It searchs for <name>$theme</name>
# so if you have more then one line in your rc.xml that matches that for some
# reason then you may have problems. BACK UP YOUR RC.XML BEFORE TRYING THIS. If
# you misconfigure something, it COULD screw up your rc.xml, though I doubt it
#  will. I've tried putting as much fail safe into this as possible, and it
# works quite well if you've configured everything properly.

THEME_PATH="/usr/share/themes/:$HOME/.local/share/themes/"
RC_PATH="$HOME/.config/openbox/rc.xml"
SCRIPT_PATH="$HOME/misc/scripts/theme"
BINNAME="openbox"
#========== END USER VARIABLES =============

IFS=:
THEMES=`find $THEME_PATH -name openbox-3 -printf '%h\n'|while read x;do basename "$x";done|sort -f`
IFS=$'\n'

rcfind() {
for RC in $THEMES; do
  grep -q "<name>$RC</name>" "$RC_PATH" && break
  unset RC
done
}

case "$1" in
menu)
rcfind
echo "<openbox_pipe_menu>"
for ITEM in $THEMES; do
  if [ "$ITEM" = "$RC" ]; then
    LABEL="&lt;-$ITEM"
  else
    LABEL="$ITEM"
  fi
  echo "  <item label=\"$LABEL\">"
  echo "    <action name=\"execute\"><execute>$SCRIPT_PATH apply \"$ITEM\"</execute></action>"
  echo "  </item>"
done
echo "</openbox_pipe_menu>"
;;
apply)
if [ -z "$2" ]; then
  echo "ERROR: No theme name specified."
  exit 1
fi
rcfind
if [ -z "$RC" ]; then
  echo "Couldn't find theme in RC file. Check theme path. If necessary, manually change theme to one in your theme path"
  exit 1
fi

for THEME in $THEMES; do
  if [ "$2" = "$THEME" ]; then
    sed -i s:"<name>$RC</name>":"<name>$THEME</name>": "$RC_PATH" 2> /dev/null
    foundtheme=1
    break
  fi
done

if [ -z $foundtheme ]; then
  echo "Theme not found. Check your theme path and try again"
  exit 1
fi

killall -USR2 "$BINNAME"
;;
*)
echo "Usage: {menu|apply [theme]}"
echo "Theme list:" $THEMES
;;
esac