#! /bin/sh
#
# rc.pwrstatd: This shell script takes care of starting and stopping
#                   standalone pwrstatd.
#
# runlevel: 2345, start priority 99, stop priority 99
# description: PowerPanel for Linux is a software program that monitors 
#              the status of your CyberPower Systems UPS.
# daemon name: pwrstatd
# configuraion file: /etc/pwrstatd.conf

PWRSTATD_BIN=/usr/sbin/pwrstatd
PROG=pwrstatd
VERSION="1.4.2"
RETVAL=0
RESULT=0

test -x $PWRSTATD_BIN || { echo "$PWRSTATD_BIN not installed";
	if [ "$1" = "stop" ]; then exit 0;
	else exit 5; fi; }

status() {
	# check pwrstatd process status	
	# CMD=`ps aux | grep "\\</usr/sbin/pwrstatd\\>"`
	CMD=`ps aux | grep "/usr/sbin/pwrstatd" | grep -v "grep"`	# without grep command
	if [ ${#CMD} != 0 ]; then					#check string length
	    if [ "$1" = "status" ]; then				# check status
		# daemon is running
		RESULT=1
	    fi
	    if [ "$1" = "reload" ]; then  # reload
		set -- $CMD						# set result as variable $1 ~ $9(max)
		kill -HUP $2						# $2 denote process ID(PID)
		RETVAL=$?
		RESULT=1
	    fi
	else
	    # daemon is not running
	    RESULT=0
	fi
	RETVAL=$?
	return $RETVAL
}

start() {
	status status							# query daemon status
	if [ $RESULT = 0 ]; then
		# Start daemon
#		echo -n $"Starting ${PROG}..."
		$PWRSTATD_BIN &						# run in background
		RETVAL=$?
	fi
	return $RETVAL
}

stop() {
	# Stop daemon
#	echo -n $"Stopping ${PROG}..."
	CMD=`ps aux | grep "/usr/sbin/pwrstatd" | grep -v "grep"`
	if [ ${#CMD} != 0 ]; then					# string length
		set -- $CMD						# set result as variable $1 ~ $9(max)		
		kill -TERM $2						# $2 denote process ID(PID)
		RETVAL=$?
	fi
	return $RETVAL
}

check() {
	if [ $RETVAL = 0 ]; then
		echo " done."
	else
		echo " fail."
	fi
}

case "$1" in
    start)
	echo -n "Starting $PROG $VERSION"
	start
	check
	;;
    stop)
	echo -n "Stopping $PROG $VERSION"
	stop
	echo
	check
	;;
    restart)
	$0 stop
	$0 start
	check
	;;
    reload)
	echo -n "Reload service $PROG $VERSION"	
	status reload
	if [ $RESULT = 0 ]; then
		echo -n "${PROG} is not running"
	else
		echo -n "${PROG} is reloading"
	fi
	echo
	check
	;;
    status)
	echo -n "Check service status $PROG $VERSION"	
	status status
	if [ $RESULT = 0 ]; then
		echo -n "   unused"
	else
		echo -n "   running"
	fi
	echo
	check	
	;;
    *)
	echo "Usage: $0 {start|stop|status|restart|reload}"
	exit 1
	;;
esac

exit 0
