#!/bin/bash

export TEXTDOMAIN=jwm
export OUTPUT_CHARSET=UTF-8

#check is X is runnning
[ ! "`grep -F 'xwin' <<< $(ps -eo pid,command)`" ] && SKIP_RESTART=true

backup (){
	cp -f $HOME/.jwm/backup/jwmrc-tray1 $HOME/.jwm/jwmrc-tray1
	cp -f $HOME/.jwm/backup/jwmrc-tray2 $HOME/.jwm/jwmrc-tray2
	cp -f $HOME/.jwm/backup/jwmrc-tray3 $HOME/.jwm/jwmrc-tray3
	cp -f $HOME/.jwm/backup/jwmrc-tray4 $HOME/.jwm/jwmrc-tray4
	cp -f $HOME/.jwm/backup/jwmrc-tray5 $HOME/.jwm/jwmrc-tray5
	cp -f $HOME/.jwm/backup/jwmrc-tray6 $HOME/.jwm/jwmrc-tray6
	cp -f $HOME/.jwm/backup/jwmrc-tray7 $HOME/.jwm/jwmrc-tray7
	cp -f $HOME/.jwm/backup/jwmrc-tray8 $HOME/.jwm/jwmrc-tray8
	cp -f $HOME/.jwm/backup/jwmrc-personal $HOME/.jwm/jwmrc-personal
	cp -f $HOME/.jwm/backup/jwmrc-corners $HOME/.jwm/jwmrc-corners
	cp -f $HOME/.jwm/backup/jwmrc-theme $HOME/.jwm/jwmrc-theme
}
export -f backup

while [ $# != 0 ]; do
	I=1
	while [ $I -lt `echo $# | wc -c` ]; do
		case $* in
			*-backup*) backup;;
			*-no_restart*) SKIP_RESTART=true;;
		esac
		shift
		I=$(($I+1))
	done
done

if [ "`grep -F 'warning:' <<< "$(LANG=C jwm -p 2>&1)"`" ]; then
	TMP="`jwm -p 2>&1 | tr -d '"'`"
	/usr/lib/gtkdialog/box_ok JWM error "$(gettext 'The window manager reports that something is wrong with your latest settings, and will roll back to the last backup.')" " " "$TMP"
	backup
else
	cp -f $HOME/.jwm/jwmrc-tray1 $HOME/.jwm/backup/jwmrc-tray1
	cp -f $HOME/.jwm/jwmrc-tray2 $HOME/.jwm/backup/jwmrc-tray2
	cp -f $HOME/.jwm/jwmrc-tray3 $HOME/.jwm/backup/jwmrc-tray3
	cp -f $HOME/.jwm/jwmrc-tray4 $HOME/.jwm/backup/jwmrc-tray4
	cp -f $HOME/.jwm/jwmrc-tray5 $HOME/.jwm/backup/jwmrc-tray5
	cp -f $HOME/.jwm/jwmrc-tray6 $HOME/.jwm/backup/jwmrc-tray6
	cp -f $HOME/.jwm/jwmrc-tray7 $HOME/.jwm/backup/jwmrc-tray7
	cp -f $HOME/.jwm/jwmrc-tray8 $HOME/.jwm/backup/jwmrc-tray8
	cp -f $HOME/.jwm/jwmrc-personal $HOME/.jwm/backup/jwmrc-personal
	cp -f $HOME/.jwm/jwmrc-corners $HOME/.jwm/backup/jwmrc-corners
	cp -f $HOME/.jwm/jwmrc-theme $HOME/.jwm/backup/jwmrc-theme
fi
[ "$SKIP_RESTART" != "true" ] && jwm -restart
