#!/bin/sh

# Used to start and stop the ProPBM Bridge

APP_CANON=`readlink -f $0`
APP_HOME=`dirname $APP_CANON`/..

cd $APP_HOME/bin

APP_NAME=commander

APP_LIB=../lib
APP_LOG=../var/log
APP_RESOURCES=../etc
APP_PID=../var/run/commander.pid
APP_ENV=../etc/commander.env

APP_MAIN=net.gethos.commander.application.Commander

CLASSPATH=
CLASSPATH=$CLASSPATH:$APP_LIB/gethos-util.jar
CLASSPATH=$CLASSPATH:$APP_LIB/gethos-commander.jar
# the tests lib is currently needed for the dummy handler
CLASSPATH=$CLASSPATH:$APP_LIB/gethos-commander-tests.jar
CLASSPATH=$CLASSPATH:$APP_RESOURCES

COMMANDERHOME_DEF=-Dgethos.commander.home=$APP_HOME
JDEF="$COMMANDERHOME_DEF"

if [ -f $APP_ENV ]; then source $APP_ENV; fi

export CLASSPATH
export JAVA_HOME

if [ -z "$JAVA_HOME" -o ! -d "$JAVA_HOME" ]; then
	JAVA_HOME=/opt/sun-jdk-1.5.0.08
fi

if [ ! -d "$JAVA_HOME" ]; then
	JAVA_HOME=/opt/jre1.5.0_09
fi

if [ ! -d "$JAVA_HOME" ]; then
	echo "unable to find a suitable JAVA_HOME"
	exit 1
fi

function start()
{
	if [ -e $APP_PID ]; then
		CURRENT_PID=`cat $APP_PID`
		echo "There is either a copy of the application running with pid $CURRENT_PID,"
		echo "or the process shut down unexpectedly. Please check and if necessary"
		echo "remove $APP_PID manually."
		exit 1
	fi

	touch $APP_PID

	if [ ! -w $COMMANDER ]; then
		echo "Unable to create pid file $APP_PID."
		echo "Please resolve the problem in order to start the bridge"
		exit 1
	fi

	echo "Starting Application..."
	echo "Java Home: " $JAVA_HOME
	echo "Application Home: " $APP_HOME

	$JAVA_HOME/bin/java $JDEF -classpath $CLASSPATH $APP_MAIN $* 1>$APP_LOG/$APP_NAME.stdout 2>$APP_LOG/$APP_NAME.stderr &

	echo "$!" > $APP_PID
}

function stop()
{
	if [ ! -r $APP_PID ]; then
		echo "Unable to read the pid from $APP_PID."
		echo "The process will not be requested to stop"
		exit 1
	fi

	CURRENT_PID=`cat $APP_PID`
	if [ -z "$CURRENT_PID" ]; then
		echo "The pid retieved from $APP_PID was blank"
		echo "The process will not be requested to stop"
		exit 1
	fi

#	COUNT=`ps p $CURRENT_PID|grep "^[[:space:]]*$CURRENT_PID"|wc -l|awk '{print $1}'`
#	if [ "$COUNT" != "1" ]; then
#		echo "The process $CURRENT_PID is not running"
#		echo "The process will not e requested to stop"
#		exit 1
#	fi

	if kill $CURRENT_PID; then
		rm $APP_PID
	else
		echo "Failed to send TERM signal to PID $CURRENT_PID"
		echo "Maybe $APP_PID is a stale pid file."
	fi

}

case $1 in
	start)
		shift 1
		start $*
	;;
	stop)
		shift 1
		stop $*
	;;
	*) echo "Unknown action '$1'. Usage: $0 (start|stop)"
esac
