#!/bin/bash
PATH=/usr/bin:/bin:$PATH
EG_BIN=/opt/egvmagent/bin
export EG_BIN PATH 
#============================================================================
# stop_agent: shell script that stops eG VMAgent
#============================================================================
if [ -r  $EG_BIN/.eGurkha_pid ]
then
	pid=`grep "agent_pid" $EG_BIN/.eGurkha_pid | cut -d '=' -f2`
	if [ "$pid" ]
	then
		kill -9 "$pid" > /dev/null 2>&1

		# after killing the agent remove the agent_pid entry from the file .eGurkha_pid
		grep -v "vmagent_pid" $EG_BIN/.eGurkha_pid >  $EG_BIN/temp
		cp $EG_BIN/temp $EG_BIN/.eGurkha_pid
		rm -f $EG_BIN/temp
	fi 
fi

pid_list=`ps -e -o pid,args | grep "EgInsideViewServer" | grep -v grep | grep "java " | awk '{print $1}'` 
#get the list of pids 
if [ "$pid_list" ] 	# if EgInsideViewServer is running
then
	for pid in $pid_list    # for each pid
	do
		# kill each child
		kill -9 $pid > /dev/null 2>&1 
	done
fi

pid_list=`ps -aef -opid,args 2>/dev/null | grep "EgInsideViewServer" | grep -v grep | grep jre |  awk '{print $1}'` 2>/dev/null 
#get the list of pids 
if [ "$pid_list" ] 	# if EgInsideViewServer is running
then
	for pid in $pid_list    # for each pid
	do
		# kill each child
		kill -9 $pid > /dev/null 2>&1 
	done
fi

/opt/egvmagent/bin/egvmagentmon stop

pid_list=`ps -aef -opid,args 2>/dev/null | grep "egvmagentmon" | grep -v grep | grep jre |  awk '{print $1}'` 2>/dev/null 
#get the list of pids 
if [ "$pid_list" ] 	# if EgInsideViewServer is running
then
	for pid in $pid_list    # for each pid
	do
		# kill each child
		kill -9 $pid > /dev/null 2>&1 
	done
fi

if [ -z "$1" ]
then
	echo "*************************************************"
	echo "The eG VMAgent has been stopped successfully."
	echo "*************************************************"
fi

