#!/bin/sh
#
# @(#)hbsarc	05.00
#
# All Rights Reserved, Copyright(c) 2005, Hitachi Ltd.
#
#
# HBase Agent for Linux (start/stop script)
#

# Allowed exit values:
#	0 = success; causes "OK" to show up in checklist.
#	1 = failure; causes "FAIL" to show up in checklist.
#	2 = skip; causes "N/A" to show up in the checklist.
#	3 = reboot; causes the system to be rebooted after execution.

rval=0

set_return() {
	x=$?
	if [ $x -ne 0 ]; then
		echo "ERROR: starting $1, exit code: $x."
		rval=1
	fi
}

killproc() {
    /opt/HDVM/HBaseAgent/bin/hbsasrv stop -f
}

findproc() {
	pid=`ps -e | grep "$1" | grep -v "_$1" | grep -v "$1_" | sed -e 's/^  *//' -e 's/ .*//'`
}

waitproc() {
	for int in 0 1 2 3 4 5 6 7	# max about 30 sec.
	do
		sleep $int
		findproc $1
		if [ "$pid" = "" ]; then
			return
		fi
	done
	echo "ERROR: stopping, $1 failed."
	rval=1
}

case $1 in

'start_msg')
	echo "Start HBase Agent for Linux"
	;;

'stop_msg')
	echo "Stop HBase Agent for Linux"
	;;

'start')
	#
	# Starting agent process.
	#
	if [ -f /etc/hbsaconf ]
	then
		. /etc/hbsaconf
	else
		echo "ERROR: /etc/hbsaconf defaults file MISSING"
	fi

	daemon=hbsasrv
	if [ -x /opt/HDVM/HBaseAgent/bin/$daemon ]; then
		if [ "$HBSASRV" -eq 1 ]
		then
			/opt/HDVM/HBaseAgent/bin/$daemon start ; set_return $daemon;
		else
			rval=2
		fi
	else
		echo "ERROR: cannot find the $daemon."
		rval=2
	fi
	if [ $rval -ne 0 ]; then
		exit $rval
	fi
	;;

'stop')
	#
	# Stopping agent process.
	#
	daemon=hbsa_service
	killproc -TERM $daemon
	waitproc $daemon
	if [ $rval -ne 0 ]; then
		exit $rval
	fi
	;;

*)
	echo "ERROR: usage: $0 {start|stop|start_msg|stop_msg}"
	rval=1
	;;

esac

exit $rval
