#! /bin/sh
#
# apcupsd      This shell script takes care of starting and stopping
#	       the apcupsd UPS monitoring daemon.
#
# chkconfig: 2345 20 99
# description: apcupsd monitors power and takes action if necessary
#
APCPID=/var/run/apcupsd.pid
DISTVER="5.2"

return="  Done."


case "$1" in
    start)
	rm -f /etc/apcupsd/powerfail
	rm -f /etc/nologin
	echo -n "Starting apcupsd power management"
	/usr/local/sbin/apcupsd --kill-on-powerfail || return="  Failed."
	echo -e "$return"
    ;;
    stop)
	echo -n "Stopping apcupsd power management"
	if [ -f ${APCPID} ]; then
		THEPID=`cat ${APCPID}`
		kill ${THEPID} || return=" Failed."
		rm -f ${APCPID}
	else
		return=" Failed."
	fi
	echo -e "$return"
    ;;
    restart)
	if [ -f $APCPID ]; then
		pid="`cat $APCPID`"
	else
		pid=''
	fi
	$0 stop
	if [ "x$pid" != "x" ]; then
		echo "waiting for apcupsd to exit "
		while true; do
			ps auxww | awk '{ print $2; }' | egrep -qe "^$pid\$"
			if [ $? -ne 0 ]; then
				echo
				break
			fi
			echo -n .
			sleep 1
		done
	fi
	$0 start
    ;;
    status)
       /usr/local/sbin/apcaccess status
    ;;
    *)
    echo "Usage: $0 {start|stop|restart|status}"
    exit 1
esac

exit 0
