#!/bin/sh
#
# chkconfig: 2345 10 90
# description: The nut daemon automatically starts a shutdown
# processname: upsd
# config: /etc/nut/

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

# Get config.
if [ -f /etc/sysconfig/nut ]; then
    . /etc/sysconfig/nut
else
    exit 1
fi

if [ "$MODEL" = "NONE" ]; then 
  echo "NUT has not been configured in /etc/sysconfig/nut"
  exit 0
fi


# this maybe should be set from the configure stuff, but currently
# is not - so make sure it matches
DRIVERPATH=/bin
POWERDOWNFLAG=/etc/killpower

# See how we are called.
case "$1" in
  start)
	if [ "$HOST" = "localhost" ]; then
	    echo -n "Starting $MODEL: "
	    if [ -f $DRIVERPATH/$MODEL -a -x $DRIVERPATH/$MODEL ]; then
		daemon $DRIVERPATH/$MODEL $OPTIONS $DEVICE 
		echo ""
	    else
		failure "$DRIVERPATH/$MODEL - no driver"
		echo ""
		exit 255
	    fi

	    echo -n "Starting UPS daemon: "
	    daemon upsd
	    echo ""

	    echo -n "Starting UPS monitor (master): "
	    daemon upsmon $HOST master
	    echo ""
	else
	    echo -n "Starting UPS monitor (slave): "
	    daemon upsmon $HOST slave
	    echo ""
	fi

	touch /var/lock/subsys/nut
	;;
  stop)
	echo -n "Stopping UPS monitor: "
	killproc upsmon
	echo ""

	if [ "$HOST" = "localhost" ]; then
	    echo -n "Shutting down UPS daemon: "
	    killproc upsd
	    echo ""

	    echo -n "Shutting down $MODEL: "
	    killproc $MODEL
	    echo ""
	fi
	rm -f /var/lock/subsys/nut
	;;
    powerdown)
	if [ -f $POWERDOWNFLAG ]; then
	    if [ "$HOST" = "localhost" ]; then
		echo -n "Instructing $MODEL to powerdown: "
		if [ -f $DRIVERPATH/$MODEL -a -x $DRIVERPATH/$MODEL ]; then
		    daemon $DRIVERPATH/$MODEL $OPTIONS -k $DEVICE 
		    echo ""
		else
		    failure "$DRIVERPATH/$MODEL - no driver"
		    echo ""
		    exit 255
		fi
	    else
		echo  "Cannot instruct UPS to powerdown"
	    fi
	fi

	touch /var/lock/subsys/nut
	;;
  restart)
	$0 stop
	$0 start
	;;
  status)
	if [ "$HOST" = "localhost" ]; then
	    status upsd
	    status $MODEL
	fi
	status upsmon
	;;
  *)
	echo "Usage: nut {start|stop|powerdown|restart|status}"
	exit 1
esac

