#!/bin/sh
#
# NUT:
#   Enable/Disable the network UPS tools client
#
# chkconfig: off 17 30
# description: NUT client
#

UPSMON=/opt/nut/sbin/upsmon
UPSMON_PARAM='-p'

#
# Log action
#
NUT_log() {
   echo "$1"
   logger -t NUT "$1"
}

create_config() {
   UPS_NAME="$(esxcfg-advcfg -q -g /UserVars/NutUpsName)"
   UPS_USER="$(esxcfg-advcfg -q -g /UserVars/NutUser)"
   UPS_PASS="$(esxcfg-advcfg -q -g /UserVars/NutPassword)"
   UPS_FINALDELAY="$(esxcfg-advcfg -q -g /UserVars/NutFinalDelay)"
   UPS_SENDMAIL="$(esxcfg-advcfg -q -g /UserVars/NutSendMail)"
   UPS_MAILTO="$(esxcfg-advcfg -q -g /UserVars/NutMailTo)"
   UPS_SMTPRELAY="$(esxcfg-advcfg -q -g /UserVars/NutSmtpRelay)"
   UPS_MINSUPPLIES="$(esxcfg-advcfg -q -g /UserVars/NutMinSupplies)"
   UPS_ONBATTDELAY="$(esxcfg-advcfg -q -g /UserVars/NutOnBatteryDelay)"

   cat /opt/nut/etc/upsmon.conf.template > /opt/nut/etc/upsmon.conf

   for i in ${UPS_NAME}
   do
      echo "MONITOR ${i} 1 ${UPS_USER} ${UPS_PASS} secondary" >> /opt/nut/etc/upsmon.conf
   done

   echo "FINALDELAY ${UPS_FINALDELAY}" >> /opt/nut/etc/upsmon.conf
   echo "MINSUPPLIES ${UPS_MINSUPPLIES}" >> /opt/nut/etc/upsmon.conf

   sed -e "s/@UPS_SENDMAIL@/$UPS_SENDMAIL/g" \
       -e "s/@UPS_MAILTO@/$UPS_MAILTO/g" \
       -e "s/@UPS_SMTPRELAY@/$UPS_SMTPRELAY/g" \
       -e "s/@UPS_ONBATTDELAY@/$UPS_ONBATTDELAY/g" \
       -e "s/@UPS_NAME@/$UPS_NAME/g" \
       -e "s/@UPS_MINSUPPLIES@/$UPS_MINSUPPLIES/g" \
       /opt/nut/etc/notify.conf.template > /opt/nut/etc/notify.conf
}

start() {
   if [ -z "$(pidof -xs "${UPSMON}")" ] ; then
      create_config
      ${UPSMON} ${UPSMON_PARAM}
      NUT_log "NUT client started"
   else
      NUT_log "NUT client already running"
   fi
}

stop() {
   if [ -n "$(pidof -xs "${UPSMON}")" ] ; then
      ${UPSMON} -c stop
      NUT_log "NUT client stopped"
      rm -f /opt/nut/etc/upsmon.conf
      rm -f /opt/nut/etc/notify.conf
   else
      NUT_log "NUT client is not running"
   fi
}

case "${1}" in
   "start")
      start
   ;;
   "stop")
      stop
   ;;
   "status")
      if [ -n "$(pidof -xs "${UPSMON}")" ] ; then
         NUT_log "NUT client is running"
         exit 0
      else
         NUT_log "NUT client is not running"
         exit 3
      fi
   ;;
   "restart")
      stop
      start
   ;;
   *)
      echo "Usage: $(basename ${0}) {start|stop|status|restart}"
      exit 1
   ;;
esac

