#! /bin/sh
#
# nut    Script to start and stop Network UPS Tools daemon(s)

# comment out the next three lines once you have configured Network UPS Tools
#echo "You must configure Network UPS Tools by modifying"
#echo "the configuration files in the /etc/nut directory."
#exit 0

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
NAME=nut
DESC="Network UPS Tools"

set -e

test -f /etc/nut/debian.conf || exit 0
source /etc/nut/debian.conf

case "$1" in
  start)
    echo "Starting $DESC"
    if [ "$MODE" = MASTER ] ; then
      # start all the UPS-specific daemons (apcsmart, genericups, etc.)
      for cmd_line in "`cat /etc/nut/upsd.conf | grep '^UPS' | cut -d' ' 
-f4-`" ; do
        if [ -n "$cmd_line" ] ; then
 	  DAEMON=`echo $cmd_line | cut -d' ' -f1`
          ARGUMENTS=`echo $cmd_line | cut -d' ' -f2-`
          start-stop-daemon --start --verbose --exec /sbin/$DAEMON -- 
$ARGUMENTS
	fi
      done
      # start the ups daemon (server)
      start-stop-daemon --start --verbose --exec /sbin/upsd
      # start the ups monitoring daemon (client)
      start-stop-daemon --start --quiet --exec /sbin/upsmon -- 127.0.0.1
    else
      # start the ups monitoring daemon (client)
      start-stop-daemon --start --quiet --exec /sbin/upsmon -- $MASTER slave
    fi
    ;;
  stop)
    echo "Stopping $DESC"
    # stop the ups monitoring daemon
    start-stop-daemon --stop --oknodo --verbose --exec /sbin/upsmon
    if [ "$MODE" = MASTER ] ; then
      for DAEMON in `cat /etc/nut/upsd.conf | grep '^UPS' | cut -d' ' -f4` ; do
        if [ -n "$DAEMON" ] ; then
        # stop the UPS-specific daemons
        start-stop-daemon --stop --oknodo --verbose --exec /sbin/$DAEMON
	fi
      done
      # stop the ups daemon (server)
      start-stop-daemon --stop --oknodo --verbose --exec /sbin/upsd
    fi
    ;;
  restart|force-reload)
    $0 stop
    sleep 1
    $0 start
    ;;
  poweroff)
    if [ -f /etc/killpower ] ; then
      echo "Powering off $DESC"
      if [ "$MODE" = MASTER ] ; then
      for cmd_line in "`cat /etc/nut/upsd.conf | grep '^UPS' | cut -d' ' 
-f4-`" ; do
          if [ -n "$cmd_line" ] ; then
 	    DAEMON=`echo $cmd_line | cut -d' ' -f1`
            DEVICE=`echo $cmd_line | sed 's/.*\///'`
	    # kill the poser to the various UPS
            /sbin/$DAEMON -k /dev/$DEVICE
	  fi
        done
      fi
    fi
    ;;
  *)
    N=/etc/init.d/$NAME
    echo "Usage: $N {start|stop|restart|force-reload|poweroff}" >&2
    exit 1
    ;;
esac

exit 0
