#!/bin/sh
JAVA_HOME=/opt/egurkha/jre
JAVA_LIB=/opt/egurkha/jre/lib
export JAVA_HOME JAVA_LIB
export JAVA_HOME
export JAVA_LIB
JAVA_FONT_HOME=/usr/java1.2
export JAVA_FONT_HOME
EG_HOME=/opt/egurkha
export EG_HOME

PATH=$JAVA_HOME/bin:$EG_HOME/bin:/sbin:/usr/bin:$PATH:/bin:/usr/local/bin
export PATH

CLASSPATH=.:$EG_HOME/lib/eg_plus.jar:$EG_HOME/lib/eg_util.jar:$EG_HOME/lib/eg_agent.jar:$EG_HOME/lib/jsse.jar:$EG_HOME/lib/jcert.jar:$EG_HOME/lib/jnet.jar:$CLASSPATH
export CLASSPATH

unset JAVA_TOOL_OPTIONS 2>/dev/null
unset _JAVA_OPTIONS 2>/dev/null
unset IBM_JAVA_OPTIONS 2>/dev/null

#============================================================================
# start and stop eG Agent monitor/recover
#=============================================================================
mypid=`ps -o pid= -p $$`
if [ "x$1" = "x" ] 
then
	echo "Wrong input value!"	
elif [ $1 = "stop" ]
then
	#code to get the list of pids of the zone in which agent is currently running. ie. for Solaris Zone machines
	isZone=0
	zonename=""
	if [ -f "/sbin/zonename" ] || [ -f "/usr/bin/zonename" ]
	then
		zonename=`zonename`
		isZone=1
	fi
	if [ $isZone -eq 1 ]
	then
		pid_list=`ps -z $zonename -opid,args | grep "eGAgentmon" | grep -v "grep"| awk '{print $1}'`
	else 
		pid_list=`ps -e -opid,args | grep "eGAgentmon" | grep -v "grep"| awk '{print $1}'`
	fi
	
	#get the list of pids
	if [ "$pid_list" ]      # if Agent Recovery is running
	then
        	for pid in $pid_list    # for each pid
        	do
                	# kill each child
                    if test  $pid != $mypid ; then
                         kill -9 $pid > /dev/null 2>&1
                    fi

        	done
	fi
	# to kill the sleep command when eGAgentmon is stopped

	userName=`id | awk '{print $1}' | cut -d'(' -f2 | cut -d')' -f1`

	#code to get the list of pids of the zone in which agent is currently running. ie. for Solaris Zone machines
	if [ $isZone -eq 1 ]
	then
		pid_list=`ps -z $zonename -o pid,user,args | grep "sleep 299" | grep "$userName" | grep -v "grep"| awk '{print $1}'`
	else 
		pid_list=`ps -e -o pid,user,args | grep "sleep 299" | grep "$userName" | grep -v "grep"| awk '{print $1}'`	
	fi
	
	#get the list of pids
	if [ "$pid_list" ]      # if Recovery is running
	then
		for pid in $pid_list    # for each pid
		do
		# kill each child
			kill -9 $pid > /dev/null 2>&1
		done
	fi
	# code for killing sleep ends here
elif [ $1 = "start" ]
then
	while :
	do
		sleep 299
		java -client EgCheckAgent 
	done
else
	echo "Wrong input value!"	
fi

