#! /bin/sh
#
# apcupsd      This shell script takes care of starting and stopping
#	       the apcupsd UPS monitoring daemon.
#
# chkconfig: 2345 33 90
# description: apcupsd monitors power and takes action if necessary
#

### BEGIN INIT INFO
# Provides:          apcupsd
# Required-Start:    $network
# Required-Stop:     $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start apcupsd at boot time
# Description:       Run the apcupsd UPS monitoring daemon.
### END INIT INFO

APCPID=/var/run/apcupsd.pid
LOCKFILE=/var/lock/subsys/apcupsd
RETVAL=0
OPTIONS=""

# Source function libarary
. /etc/init.d/functions

# Source service configuration.
SourceIfNotEmpty /etc/sysconfig/apcupsd

[ -x /sbin/apcupsd -a -s /etc/apcupsd/apcupsd.conf ] || exit

start()
{
	rm -f /etc/apcupsd/powerfail /etc/nologin
	cd /var/lib/apcupsd
	start_daemon --pidfile "$APCPID" --lockfile "$LOCKFILE" -- /sbin/apcupsd -f /etc/apcupsd/apcupsd.conf "$OPTIONS"
	RETVAL=$?
}

stop()
{
	DELAYTIME=`/etc/apcupsd/get_killpower_delay`
	stop_daemon --pidfile "$APCPID" --lockfile "$LOCKFILE" -- /sbin/apcupsd
	RETVAL=$?
	UPSCTL=/etc/apcupsd/apccontrol
	if [ -x "$UPSCTL" -a -f /etc/apcupsd/powerfail ]; then
		if [ $[ $DELAYTIME > 0 ] == 1 ]; then
			echo "Attempting to turn the UPS off (if success UPS will be off after $DELAYTIME sec)..."
			"$UPSCTL" killpower
		fi
	fi
}

restart()
{
	stop
	start
}

# See how we were called.
case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart|reload)
		restart
		;;
	condstop)
		if [ -e "$LOCKFILE" ]; then
			stop
		fi
		;;
	condrestart)
		if [ -e "$LOCKFILE" ]; then
			restart
		fi
		;;
	status)
		status --pidfile "$PIDFILE" -- apcupsd
		RETVAL=$?
		;;
	*)
		echo "Usage: ${0##*/} {start|stop|reload|restart|condstop|condrestart|status}"
		RETVAL=1
esac

exit $RETVAL
