#!/bin/sh
#
# chkconfig: 2345 99 5
# description: The RSCD Agent is used by the Network Shell
# processname: rscd
#
NSHDIR=/opt/bmc/bladelogic/NSH
LD_LIBRARY_PATH=${LD_LIBRARY_PATH:=}${LD_LIBRARY_PATH:+:}/opt/bmc/bladelogic/NSH/lib
export LD_LIBRARY_PATH


HAVE_READLINK=0
which readlink >/dev/null 2>&1
if test "$?" -eq 0
then
	HAVE_READLINK=1
fi

#
# Start the RSCD Daemon
#

RSCDHOME=/opt/bmc/bladelogic/NSH
export RSCDHOME

stop_rscd_proc()
{
	RSCD_PIDS=`ps -ef | grep "rsc[dw]" | grep -v grep | awk ' { print $2 }'`
	if test -n "$RSCD_PIDS"
	then
		PIDS=
		for i in $RSCD_PIDS
		do
			if test -f "/proc/$i/exe"
			then
				if test "$HAVE_READLINK" -eq 1
				then
					EXE_PATH=`readlink /proc/$i/exe`
				else
					EXE_PATH=`ls -l /proc/$i/exe | awk -F'-> ' '{print $2}'`
				fi
				if test $? -eq 0
				then
					PID_DIR=`dirname \`dirname $EXE_PATH\``
					if test "$RSCDHOME" = "$PID_DIR"
					then
						PIDS="$PIDS $i"
					fi
				fi
			fi
		done
		if test -n "$PIDS"
		then
			kill -9 `echo $PIDS`
		fi
	fi
}


case $1 in
stop)
	ps -ef | grep "rsc[dw]" | grep -v grep | awk ' { print $2 }' >/dev/null

	if test $? -eq 0
	then
		echo "Stopping Remote System Call Daemon (RSCD) ..."
		stop_rscd_proc

		# Sometimes the watcher process gives us trouble.
		# Try stopping a second time just to be sure.
		stop_rscd_proc
		echo
	fi
	;;

start)
	if test -f $RSCDHOME/bin/rscd 
	then
		echo -n "Starting Remote System Call Daemon (RSCD) ..."
		(cd $RSCDHOME; bin/rscd < /dev/null)
                sleep 4   #
                          # Hope this is enough to display all the
                          # messages during rscd startup.
                          #
		echo
	fi
	;;

*)
	echo "Usage: $0 {start|stop}"
	;;
esac
