#!/bin/sh
#
# chkconfig: 2345 30 90
#
# 2022-01-04 Jim Klimov <jimklimov+nut@gmail.com>
#  Updated .in template, double-quoted variable expansions
#
# 2003-01-31 Antonino Albanese <al.an@monkeysweb.net>
#  Removed all old statements
#  start programs as user nut
#  new style starting and stopping upsd
#  added reload option
#  use of /etc/sysconfig/ups for POWERDOWNFLAG variable retrieving
#
# 2002-02-07 Nigel Metheringham <Nigel.Metheringham@InTechnology.co.uk>
#  made ups.conf pre-eminant, added new upsdrvctl functions, targeted for RH7.2, should
#  work OK on RH 6.x, 7.x
# 2001-10-24 Peter Bieringer <pb@bieringer.de>
#  enhancements for new style drivers and controls, tested on a RHL 7.1.93 system
#
# description: NUT upsd and its drivers directly monitor a ups and \
#	make information from it available to other programs
# processname: upsd
# config: @CONFPATH@/upsd.conf
# config: @CONFPATH@/ups.conf

PATH="/sbin:/bin:/usr/sbin:/usr/bin"
export PATH

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

# POWERDOWNFLAG *must* match that in upsmon.conf
# Loading POWERDOWNFLAG from /etc/sysconfig/ups
DRIVERPATH="@DRVPATH@"
NUT_SBINDIR="@SBINDIR@"
if [ -f /etc/sysconfig/ups ]; then
  . /etc/sysconfig/ups
else
  POWERDOWNFLAG="@POWERDOWNFLAG@"
  NUTUSER="@RUN_AS_USER@"
fi
UPSDCONF="@CONFPATH@/upsd.conf"
UPSCONF="@CONFPATH@/ups.conf"

if [ -n "$DRIVERPATH" -a -d "$DRIVERPATH" ]; then
  PATH="$DRIVERPATH:$PATH"
fi
if [ -n "$NUT_SBINDIR" -a -d "$NUT_SBINDIR" ]; then
  PATH="$NUT_SBINDIR:$PATH"
fi

# if there are no config file, bail out
[ -f "$UPSDCONF" ] && [ -f "$UPSCONF" ] || exit 0

NUT_QUIET_INIT_UPSNOTIFY=true
export NUT_QUIET_INIT_UPSNOTIFY

runcmd() {
   echo -n "$1 "
   shift
   if [ "$BOOTUP" = "color" ]; then
      $* && echo_success || echo_failure
   else
      $*
   fi
   echo
}

# See how we are called.
case "$1" in
  start)
	# new style drivers uses 'upsdrvctl'
	echo -n "NUT Starting UPS model drivers: "
	# starting all drivers as nut user
	daemon --user "$NUTUSER" "`which upsdrvctl`" start
	echo
	if [ $? -eq 0 ]; then
		echo -n "NUT Starting UPS daemon: "
		# starting as nut user
		daemon upsd -u "$NUTUSER"
		echo
		touch /var/lock/subsys/upsd
	fi
	;;

  stop)
	# new style upsd stop
	action "NUT Stopping UPS daemon" \
	upsd -c stop
	# new style drivers uses 'upsdrvctl'
	action "NUT Stopping UPS model drivers" \
	upsdrvctl stop

	rm -f /var/lock/subsys/upsd
	;;

  powerdown)
	# new style drivers
	runcmd "NUT powerdown of attached UPS(es)" upsdrvctl shutdown
	;;

  restart)
	$0 stop
	$0 start
	;;

  reload)
	# reloading upsd config files
	action "NUT Reloading config files" \
	upsd -c reload
	;;

  status)
	# new style drivers
	action "NUT: checking UPS model drivers" upsdrvctl status

	status upsd
	;;
  *)
	echo "Usage: upsd {start|stop|powerdown|restart|reload|status}"
	exit 1
esac
