#!/bin/ksh

# Component: webrc
#
# Description:
#  Control script of component webrc
#
# Last Updated     : $Author$
# Update Date Time : $Date$
# RCS File Name    : $RCSfile$
# RCS Revision     : $Revision$
# Locked by        : $Locker$
# Symbolic name    : $Name$
# State            : $State$

#--- INIT ------------------------------
#needs $HOME
. $HOME/etc/ctrl.main.shi

[ -f $HOME/etc/setenv.sh ] && . $HOME/etc/setenv.sh

WEBRC_PID="$HOME/var/run/webrc.pid"
WEBRC_HOME="$HOME/component/webrc"

#--- FUNC ------------------------------
do_shell_()
{
	cat <<-EndOfInlineData
	EndOfInlineData

} #do_shell_()

do_start_()
{
	if [ ! -f $WEBRC_PID ]; then	
		CWD=`pwd`
		cd $WEBRC_HOME
#    	java -jar WebRC.jar &> start.out &
    	${JAVAKIT_HOME}/java/bin/java -jar WebRC.jar &
    	JETTY_PID=$!
    	echo $JETTY_PID > $WEBRC_PID
    	echo WebRC[$JETTY_PID] started.
    	cd $CWD
    else
    	PID="`cat $WEBRC_PID`"
    	
    	if [ "$PID" != "" ]; then
			if [ `ps aux|grep $PID -c` -ne 1 ]; then
    			echo WebRC already running [pid: `cat $WEBRC_PID`]
    		else
    			rm $WEBRC_PID
    			do_start_
    		fi
    	fi
    fi
} #do_start_()

do_status_()
{
	if [ -f $WEBRC_PID ]; then
		STATUS="`$CURL_HOME/bin/curl -o /dev/null --silent --head --write-out '%{http_code}' "http://localhost:4649/webrc/call"`"
		if [ $STATUS -eq 405 ]; then
			echo OK
		else
			echo ERROR
		fi
	else
		echo STOPPED
	fi
} #do_status_()

do_stop_()
{
	if [ -f $WEBRC_PID ]; then
		PID="`cat $WEBRC_PID`"
	fi
	if [ "$PID" != "" ]; then
		if [ `ps aux|grep $PID -c` -ne 1 ]; then
			kill $PID
			sleep 1
			if [ `ps aux|grep $PID -c` -eq 1 ]; then
				rm $WEBRC_PID
				echo WebRC stopped.
			else
				echo Error stopping WebRC[$PID].
			fi
		else
			echo WebRC was not running.
			rm $WEBRC_PID
		fi
	else
		echo WebRC is not running.
	fi	
} #do_stop_()

do_restart_()
{
	if [ -f $WEBRC_PID ]; then
		PID="`cat $WEBRC_PID`"
	fi
	if [ "$PID" != "" ]; then
		if [ `ps aux|grep $PID -c` -ne 1 ]; then
			do_stop_
			sleep 1
			do_start_
			sleep 1
			do_status_
		else
			do_start_
			sleep 1
			do_status_
		fi
	else
		do_start_
		sleep 1
		do_status_
	fi	
} #do_restart_()


#--- MAIN ------------------------------
#check_action_ $1
if [ 0 = $? ]; then
	do_$1_

else
	echo "--- Component webrc [ctrl $$]: Bad command: $1" >&2
	exit 1
fi
