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

# Source function library
. /etc/rc.d/init.d/functions

# Get network config
. /etc/sysconfig/network

# Check that networking is up.
if is_yes "${NETWORKING}"; then
	if [ ! -f /var/lock/subsys/network -a "$1" != stop -a "$1" != status ]; then
		msg_network_down "UPS monitoring"
		exit 1
	fi
else
	exit 0
fi

# Get service config
if [ -f /etc/sysconfig/apcupsd ]; then
	. /etc/sysconfig/apcupsd
fi

start() {
	# Check if the service is already running?
	if [ -f /var/lock/subsys/apcupsd ]; then
		msg_already_running "APC UPS monitoring"
		return
	fi

	msg_starting "APC UPS monitoring"
	rm -f /etc/apcupsd/powerfail
	daemon $SERVICE_RUN_NICE_LEVEL /usr/sbin/apcupsd -f /etc/apcupsd/apcupsd.conf
	RETVAL=$?
	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/apcupsd
}

stop() {
	if [ ! -f /var/lock/subsys/apcupsd ]; then
		msg_not_running "APC UPS monitoring"
		return
	fi

	msg_stopping "APC UPS monitoring"
	killproc apcupsd
	rm -f /var/lock/subsys/apcupsd
}

condrestart() {
	if [ ! -f /var/lock/subsys/apcupsd ]; then
		msg_not_running "APC UPS monitoring"
		RETVAL=$1
		return
	fi

	stop
	start
}

powerdown() {
	if [ ! -f /etc/apcupsd/powerfail ]; then
		return
	fi

	show "Switching the power off"
	/etc/apcupsd/apccontrol killpower
	sleep 60
	fail
}

RETVAL=0
# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart)
	stop
	start
	;;
  try-restart)
	condrestart 0
	;;
  force-reload)
	condrestart 7
	;;
  powerdown)
	powerdown
	;;
  status)
	status apcupsd
	/usr/sbin/apcaccess status
	RETVAL=$?
	;;
  *)
	msg_usage "$0 {start|stop|restart|try-restart|force-reload|powerdown|status}"
	exit 3
esac

exit $RETVAL
