#!/bin/sh
# upsmonitor, Boone, 05/27/99
# Monitor UPS, shut down system if on battery and battery is low
#
# Modifications:
# 05/27/99 Boone      Initial coding
# 04/30/08 Boone      Updates for .deb packaging, pass community to worker
#                     scripts on command line
# End Modifications

# Initialize

	. /etc/default/upsmonitor

	POWEROUTMSG=/tmp/poweroutmsg
	POWERBACKMSG=/tmp/powerbackmsg
	DEADBATTMSG=/tmp/deadbatterymsg

	mkmsg()
	{
		why=`/usr/bin/upswhybatt $UPSHOST $COMMUNITY`
		remain=`/usr/bin/upsremainingbatt $UPSHOST $COMMUNITY | awk '{print $2}'`

		cat > $POWEROUTMSG <<EOF
Line power is out or unreliable.  The UPS is running on batteries.
$remain minutes of battery power are currently available.  If the
power is still out at $MINLEFT minutes of battery power remaining,
the system will be shut down.

Reported reason for transfer: $why
EOF

		cat > $POWERBACKMSG <<EOF
Line power has been restored.  $remain minutes of operation remain
in the batteries.
EOF

		cat > $DEADBATTMSG <<EOF
Line power is still out or unreliable.  The charge in the UPS batteries
is nearly exhausted.  The system must now be shut down, before the
UPS powers down.

Charge left: $left
Reason for transfer: $remain
EOF
	}

# Main loop

	firstmsg=TRUE
	onbatt=FALSE
	while /bin/true
	do
		if /usr/bin/upsonbatt $UPSHOST $COMMUNITY
		then
			onbatt=TRUE

			if [ $firstmsg = "TRUE" ]
			then
				firstmsg=FALSE
				mkmsg
				wall < $POWEROUTMSG
			fi

			left=`/usr/bin/upsremainingbatt $UPSHOST $COMMUNITY | awk '{print $2}'`
			if [ $left -lt $MINLEFT ]
			then
				mkmsg
				wall < $DEADBATTMSG
				shutdown -h +3 \
					"UPS batteries are nearly exhausted"
			fi
		else
			if [ $onbatt = "TRUE" ]
			then
				onbatt=FALSE
				firstmsg=TRUE
				mkmsg
				wall < $POWERBACKMSG
			fi
		fi

		sleep $SLEEPTIME
	done
