#!/bin/bash 
JAVA_HOME=/usr/java/jdk1.3.1
export JAVA_HOME
JAVA_LIB=/usr/java/jdk1.3.1/lib
export JAVA_LIB
JAVA_FONT_HOME=/usr/java/jdk1.3.1
export JAVA_FONT_HOME


LD_LIBRARY_PATH=/opt/egurkha/lib:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH

EG_HOME=/opt/egurkha
export EG_HOME

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

CLASSPATH=.:$EG_HOME/lib/eg_util.jar:$EG_HOME/manager/tomcat/webapps/final/WEB-INF/classes:$EG_HOME/lib/eg_manager.jar:$EG_HOME/lib/jsse.jar:$EG_HOME/lib/jnet.jar:$EG_HOME/lib/jcert.jar:$EG_HOME/lib/classes111.zip:$EG_HOME/lib/activation.jar:$EG_HOME/lib/mail.jar:$EG_HOME/lib/ThinTds.jar:$CLASSPATH
export CLASSPATH

#============================================================================
# start and stop eG monitor/recover
#=============================================================================
if [ "x$1" = "x" ] 
then
	echo "Wrong input value!"	
elif [ $1 = "stop" ]
then
	pid_list=`ps -e -opid,args | grep "eGmon start" | grep -v "grep" | awk '{print $1}'`
	mypid=`ps -o pid= -p $$`	
	#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
			if test  $pid != $mypid ; then
                		kill -9 $pid > /dev/null 2>&1
       		        fi
        	done
	fi
        # code to kill sleep command started by eGmon when eGmon is stopped
        userName=`id | awk '{print $1}' | cut -d'(' -f2 | cut -d')' -f1`
        pid_list=`ps -e -o pid,user,args | grep "sleep 300" | grep "$userName" | grep -v "grep"| awk '{print $1}'`
        #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 to kill sleep command ends here

elif [ $1 = "start" ]
then
	while :
	do
		sleep 300
        pid_list=`ps -e -o pid,user,args | grep "com.eg.EgCheckManager" | grep "java" | grep -v "grep"| awk '{print $1}'`
        #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

		java com.eg.EgCheckManager 
		#==========
		#Now check for defuncts and restart discovery if required
		#==========
		count_defunct=`ps -aef | grep "defunct" | grep -v "grep" |wc -l`
		if [ $count_defunct -ge 10 ]
		then	
			java com.eg.EgStartStopDisc stop
			java com.eg.EgStartStopDisc start 0
		fi
		#====== End of defunct related stuff //This is for linux only
	done
else
	echo "Wrong input value!"	
fi

