#!/bin/sh

#   Licensed Materials - Property of IBM
#   Rational ClearQuest and ClearCase
#   (C) Copyright IBM Corporation. 2005, 2012. All Rights Reserved
#   US Government Users Restricted Rights -
#   Use, duplication or disclosure restricted by GSA ADP Schedule
#   Contract with IBM Corporation

cm_home=/opt/rational/common/CM
cmprofile_log=$cm_home/profiles/cmprofile/logs/cmprofile_stop.log

ret=0
ret1=0
ret2=0

if [ -x "/bin/awk" ]; then
    AWK="/bin/awk"
elif [ -x "/usr/bin/awk" ]; then
    AWK="/usr/bin/awk"
else
    AWK="awk"
fi

# Assume success to begin with
# Ensure an appropriate path. On Linux, standard UNIX executables like ls and rm
# are typically in /bin, whereas on Solaris, HP-UX, and AIX they are
# typically in /usr/bin. We put both on the path. We also put
# the system /sbin and /usr/sbin on the path.
PATH=/bin:/usr/bin:/sbin:/usr/sbin

#
# Check the profile pid file 
# Verify that the cmprofile process is running before stopping it.
#
stop_ifrunning() 
{
	profile=$1
	profile_log=$2

	ret=0

	if [ -f "$cm_home/profiles/cmprofile/logs/server1/server1.pid" ] ; then
		# if pid file exists verify that cmprofile process is really running
		pid=`grep '[0-9]*' $cm_home/profiles/cmprofile/logs/server1/server1.pid`

		ps -ef | grep -v grep | grep cmprofile | grep "$pid" 1>/dev/null

		running=$?

		if [ $running -eq 0 ]; then
			echo "Stopping cmprofile process $pid ..."
			$cm_home/profiles/cmprofile/bin/stopServer.sh server1 >> $cmprofile_log 2>&1
			ret=1
		fi
	fi

	return $ret
}

stop_ifrunning cmprofile $cmprofile_log
ret1=$?

# If there was a cmprofile process running, double check to see if it was stopped.
if [ $ret1 -eq 1 ]; then

	sleep 5

	# Check if the cmprofile process is stopped.
	pids=`ps -ef | grep -v grep | grep cmprofile | awk '{print $2}'`

	# If necessary, kill the cmprofile
	for pid in $pids ; do
		echo killing PID $pid
		kill -9 $pid
	done
	sleep 5

	# Recheck that they are stopped
	pids=`ps -ef | grep -v grep | grep cmprofile`
	for pid in $pids ; do
		echo "Unable to kill PID $pid. You need to kill PID $pid"
	done

	if [ "${pids}" != "" ] ; then
		ret2=1
	fi

	if [ $ret2 -eq 0 ]; then
		echo "cmprofile stopped successfully"

		/opt/rational/common/IHS/bin/ihs_shutdown
	else
		ret=1

		if [ ! $ret2 -eq 0 ]; then
			echo "Failed to stop cmprofile"
			echo "Check log file $cmprofile_log"
		fi
	fi
else
	# It wasn't running.
	echo "cmprofile is not running"

fi
sleep 3

exit $ret
