#!/bin/bash

# shell script to give a frontend to starting and stopping
# the utils for the ebookwise eb-1150
RCFILE=~/.eb-bookshelfrc
LISTENPORT=1026
LINREBIP=127.0.0.1
BOOKROOT=~/Books/EB1150
eb1150PID=0
linrebPID=0
orgDir=$PWD
shutDown=0

_writeRCFILE() 
{
	echo "BOOKROOT=$BOOKROOT" > $RCFILE
	echo "LINREBIP=$LINREBIP" >> $RCFILE
	echo "LISTENPORT=$LISTENPORT" >> $RCFILE
}

_readRCFILE() 
{
echo "woot"
}

_changeRCFILE() 
{
	zenity --question \
--text="Current settings are\n \
Book root directory $BOOKROOT\n \
linreb listening port $LISTENPORT\n \
Host IP $LINREBIP\n \
Keep these settings?\n \
Press Cancel to change."

if [ $? -eq 1 ]; then
	BOOKROOT=$(zenity --entry --text="Enter Bookroot path")
	LINREBIP=$(zenity --entry --text="Enter Host IP address")
	LISTENPORT=$(zenity --entry --text="Enter Port Linreb should listen on")
fi


}

_startEB1150()
{
	if pidof eb1150
	then
		zenity --warning --text="eb1150 seems to be running already.\nTry stopping it and then try to start it again."
	else
		eb1150 &
	fi
}

_startEB1150Local() 
{
	if pidof eb1150
	then
		zenity --warning --text="eb1150 seems to be running already.\nTry stopping it and then try to start it again."
	else
		eb1150 -h $LINREBIP &
	fi
}

_stopEB1150() 
{
	if pidof eb1150
	then
		kill -s 15 `pidof eb1150`
	elif [ $shutDown -eq 0 ]; then
		zenity --info --text="eb1150 does not seem to be running."
	fi
}

_startLinreb() 
{
	if pidof linreb 
	then
		zenity --warning --text="linreb seems to be running already.\nTry stopping it and then try to start it again."
	else
		cd $BOOKROOT
		linreb -p $LISTENPORT &
	fi
}

_stopLinreb() 
{
	if pidof linreb 
	then
		kill -s 15 `pidof linreb`
	elif [ $shutDown -eq 0 ]; then
		zenity --info --text="linreb does not seem to be running."
	fi
}

_showMain()
{
	ret=1
	if pidof eb1150 
	then
		ebmess="Running"
	else
		ebmess="Not Running"
	fi
	if pidof linreb 
	then
		linmess="Running"
	else
		linmess="Not Running"
	fi
   ans=$(zenity --list --height=400 \
--text="Current Settings\n \
Bookroot $BOOKROOT\n \
Host IP  $LINREBIP\n \
Port     $LISTENPORT\n \
eb1150 is currently $ebmess\n \
linreb is currently $linmess\n \
Press Cancel to exit." \
--column="num" \
--column="Select one" 1 "Change Settings" 2 "Start Local eb1150" 3 "Start eb1150" 4 "Start linreb" \
5 "Stop eb1150" 6 "Stop linreb" 7 "Stop all and exit" \
--hide-column=1)
#exit if user pressed cancel
if [ $? -eq 1 ];then
	ans=7
fi

case $ans in
	1 ) 
		_changeRCFILE
	;;
	2 )
		_startEB1150Local
	;;
	3 )
		_startEB1150
	;;
	4 )
		_startLinreb
	;;
	5 )
		_stopEB1150
	;;
	6 )
		_stopLinreb
	;;
	7 )
		echo "Exiting"	
		ret=0
	;;
esac
return $ret

}

_quit()
{
	shutDown=1
	_stopLinreb
	_stopEB1150
	_writeRCFILE
	cd $orgDir
}

if [ -f $RCFILE ]; then
	. $RCFILE
else 
	_changeRCFILE	
fi

let end_it=1

while [ $end_it -gt 0 ]
do
	_showMain
	end_it=$?
done
_quit
exit 0

