#! /bin/sh
#
# default_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
# /etc/init.d/pwrstatd symbolic link /usr/sbin/pwrstatd

PWRSTATD_BIN=/usr/sbin/pwrstatd
PROG=pwrstatd
VERSION="1.3.3"
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  # status
	   	# daemon is existed
	   	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 existed
	   RESULT=0	   
	fi
	RETVAL=$?
	return $RETVAL
}

start() {
    # Start daemons.
    echo -n $"   starting"		 
	 status status					# query daemon status	  
	 if [ $RESULT = 0 ]; then
        	$PWRSTATD_BIN &		# run as background	 
	  	RETVAL=$?					# The $? variable denote get start daemon result
	 fi
    return $RETVAL
}

stop() {
    # Stop daemons.
    echo -n $"   stopping"
        
	 # Terminate pwrstatd process!
	 CMD=`ps aux | grep "/usr/sbin/pwrstatd" |grep -v "grep"` # without grep command
	 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
		echo
		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 "   unused"
		else
			echo -n "   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
