#! /bin/sh
#
# nut - Script to start and stop Network UPS Tools daemons

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

[ -f $DEFAULT ] || exit 0
. $DEFAULT

upsmon_pid=/var/run/nut/upsmon.pid
upsmon=/sbin/upsmon
upsd_pid=/var/run/nut/upsd.pid
upsd=/sbin/upsd
log=">/dev/null 2>/dev/null"

start_stop_server () {
  case "$START_UPSD" in
    y|Y|yes|YES|Yes)
      case "$1" in
        start)
          ! /sbin/upsdrvctl start >/dev/null 2>&1  &&  \
            echo -n " (upsdrvctl failed)"
          start-stop-daemon -S -q -p $upsd_pid -x $upsd >/dev/null 2>&1
          ;;
        stop)
          start-stop-daemon -K -o -q -p $upsd_pid -n upsd >/dev/null 2>&1
          ! /sbin/upsdrvctl stop >/dev/null 2>&1  &&  \
            echo -n " (upsdrvctl failed)"
          ;;
      esac
      ;;
    n|N|no|NO|No|*)
      return 1
      ;;
  esac
}

start_stop_client () {
  case "$START_UPSMON" in
    y|Y|yes|YES|Yes)
      case "$1" in
        start)
          start-stop-daemon -S -q -p $upsmon_pid -x $upsmon >/dev/null 2>&1
          ;;
        stop)
          start-stop-daemon -K -o -q -p $upsmon_pid -n upsmon >/dev/null 2>&1
          ;;
      esac
      ;;
    n|N|no|NO|No|*)
      return 1
      ;;
  esac
}

case "$1" in

  start)
    echo -n "Starting $DESC:"
    start_stop_server start && echo -n " upsd"
    start_stop_client start && echo -n " upsmon"
    echo "."
    ;;

  stop)
    echo -n "Stopping $DESC:"
    start_stop_server stop && echo -n " upsd"
    start_stop_client stop && echo -n " upsmon"
    echo "."
    ;;

  reload)
    $upsd   -c reload >/dev/null 2>&1
    $upsmon -c reload >/dev/null 2>&1
    ;;

  restart|force-reload)
    echo -n "Restarting $DESC:"
    start_stop_client stop
    start_stop_server stop
    sleep 5
    start_stop_server start && echo -n " upsd"
    start_stop_client start && echo -n " upsmon"
    echo "."
    ;;

  poweroff)
    flag=`sed -ne 's#^ *POWERDOWNFLAG *\(.*\)$#\1#p' /etc/nut/upsmon.conf`
    if [ -f "$flag" ] ; then
      if /sbin/upsmon -K >/dev/null 2>&1 ; then
        echo "Shutting down the UPS ..."
        sleep 5
        ! /sbin/upsdrvctl shutdown  &&  echo -n " FAILED"
        echo "."
      else
        echo "Power down flag is not set (UPS shutdown not needed)"
      fi
    else
        if [ -z "$flag" ] ; then
	  echo "##########################################################"
	  echo "## POWERDOWNFLAG is not defined in /etc/nut/upsmon.conf ##"
	  echo "##                                                      ##"
	  echo "## Please read the Manual page upsmon.conf(5)           ##"
	  echo "##########################################################"
    	fi
    fi
    ;;

  *)
    N=/etc/init.d/$NAME
    echo "Usage: $N {start|stop|reload|restart|force-reload|poweroff}" >&2
    exit 1
    ;;

esac

exit 0
