#!/bin/sh
#
# ups		NUT - Network UPS Tools daemon
#
# chkconfig:	2345 10 90
#
# description:	The ups daemon monitors an UPS and makes information about
#		it's status available to other programs
# processname:	upsd
# config:	/etc/ups/

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

# Get network config
. /etc/sysconfig/network

# Get config.
[ -f /etc/sysconfig/ups ] && . /etc/sysconfig/ups

[ -n "$PORT" ] && OPTIONS="-p $PORT"
[ -n "$TCP_PORT" ] && OPTIONS="-t $TCP_PORT"
[ -n "$BIND_ADDRESS" ] && OPTIONS="$OPTIONS -i $BIND_ADDRESS"

if [ -n "$BIND_ADDRESS" ] || [ -n "$TCP_PORT" ]; then
	# Check that networking is up.
	if is_yes "${NETWORKING}"; then
		if [ ! -f /var/lock/subsys/network ]; then
			msg_network_down ntp
			exit 1
		fi
	else
		exit 0
	fi
fi

RETVAL=0
# See how we are called.
case "$1" in
  start)
	# Check if the service is already running?
	if [ ! -f /var/lock/subsys/ups ]; then
		show "Starting UPS drivers"
		daemon /usr/lib/nut/upsdrvctl start
		RETVAL=$?
		if [ $RETVAL -eq 0 ]; then
			msg_starting "UPS network daemon"
			daemon "upsd $OPTIONS"
			RETVAL=$?
			touch /var/lock/subsys/ups
		fi
	else
		msg_already_running "UPS drivers and network daemon"
	fi
	;;
  stop)
	if [ -f /var/lock/subsys/ups ]; then
		msg_stopping "UPS daemon"
		killproc upsd
		run_cmd "Stopping UPS drivers" /usr/lib/nut/upsdrvctl stop
		rm -f /var/lock/subsys/ups
	else
		msg_not_running "UPS daemon"
	fi
	;;
  restart)
	$0 stop
	$0 start
	exit $?
	;;
  reload|force-reload)
	if [ -f /var/lock/subsys/ups ]; then
		show "Reloading UPS drivers"
		daemon /usr/lib/nut/upsdrvctl reload
		[ $? -ne 0 ] && RETVAL=7
		msg_reloading "UPS network daemon"
		daemon upsd -c reload
		[ $? -ne 0 ] && RETVAL=7
	else
		msg_not_running "UPS daemon" >&2
		exit 7
	fi
	;;
  status)
	status upsd
	RETVAL=$?
	/usr/lib/nut/upsdrvctl status
	;;
  *)
	msg_usage "$0 {start|stop|restart|reload|force-reload|status}"
	exit 3
esac 

exit $RETVAL
