#!/bin/sh
#

POWERPID=/var/run/power.pid
APCPID=/var/run/apcupsd.pid

if [ -x /sbin/shutdown ]; then
	SHUTDOWN=/sbin/shutdown
elif [ -x /sbin/shutdown.bsd ]; then
	SHUTDOWN=/sbin/shutdown.bsd
else
	echo Command shutdown or shutdown.bsd not found!
	exit 1
fi

if [ -x /usr/local/sbin/apcupsd ]; then
	APCUPSD=/usr/local/sbin/apcupsd
elif [ -x /usr/sbin/apcupsd ]; then
	APCUPSD=/usr/sbin/apcupsd
elif [ -x /sbin/apcupsd ]; then
	APCUPSD=/sbin/apcupsd
else
	echo Command apcupsd not found!
	exit 1
fi

if test "$(whoami)" != "root"; then
	printf "Sorry, you must be root to run this script." | wall
	exit 1
fi

case "$1" in
	POWEROUT)
		printf "Warning there are Power problems." | wall
		;;
	ONBATTERY)
		printf "Power Failure running on UPS." | wall
		;;
	FAILING)
		printf "Battery Power Failed, Normal Shutdown.\n" | wall
		;;
	TIMEOUT)
		printf "Online Battery timeout, Normal Shutdown.\n" | wall
		;;
	LOADLIMIT)
		printf "Battery Load Limits Reached, Normal Shutdown.\n" | wall
		;;
	RUNLIMIT)
		printf "Battery RunTime Limits Reached, Normal Shutdown.\n" | wall
		;;
	DOSHUTDOWN)
		printf "Beginning Shutdown Sequence!!!!!" | wall
		ps x | gawk '{ if (($5 == "init") && ($1 == "1")) print $6 }' \
			| cut -f2 -d[ | cut -f1 -d] \
			> /tmp/run.level.power
		if [ -f $POWERPID ]
		then
			exit 0
		else
			echo $$ > $POWERPID
			$SHUTDOWN -h now
		fi
		;;
	MAINSBACK | WAITASEC)
		printf "Power has returned..." | wall
		if [ -f $POWERPID ]; then
			printf "Attempting to cancel shutdown."
			kill $(cat $POWERPID)
			rm -f $POWERPID
			init $(cat /tmp/run.level.power)
		fi
		;;
	ANNOYME)
		printf "Power Problems Please Log Off Now!!!!" | wall
		;;
	EMERGENCY)
		printf "Emergency Shutdown, Possible Battery Failure!!!!" | wall
		$SHUTDOWN -h now
		;;
	CHANGEME)
		printf "Emergency, Batteries Have Failed!!!!\nChange Them NOW!!!!" | wall
		;;
	REMOTE)
		printf "Remote Calls, Normal Shutdown.\nBeginning Shutdown Sequence!!!!!" | wall
		$SHUTDOWN -h now
		;;
	KILL)	sleep 1
		$APCUPSD killpower
		sleep 10
		;;
	INIT)	rm -f $POWERPID
#
# apcupsd should be doing its own cleaning of lock and pid files.
# -BSC
#
#		if [ -f $APCPID ]; then
#			kill $(cat $APCPID) 1> /dev/null 2> /dev/null
#			rm -f $APCPID
#		fi
		rm -f /etc/powerfail
		rm -f /etc/powerstatus
		rm -f /etc/nologin
		echo -n "Starting APCUPSD Power Management: "
		$APCUPSD
		echo "apcupsd"
		;;
	STOP)
		echo -n "Stopping APCUPSD Power Management: "
		if [ -f $APCPID ]; then
			kill $(cat $APCPID)
			rm -f $APCPID
		fi
		echo "apcupsd"
		;;
	RESTARTME)
		echo -n "Restarting APCUPSD Power Management: "
		kill $(cat $APCPID)
		rm -f $APCPID
		rm -f $POWERPID
		rm -f /etc/powerfail
		rm -f /etc/powerstatus
		rm -f /etc/nologin
		sleep 10
		$APCUPSD
		echo "apcupsd"
		;;
	*)	echo "Usage:   ${0##*/} [POWEROUT | ONBATTERY | FAILING | TIMEOUT | LOADLIMIT | RUNLIMIT | DOSHUTDOWN | MAINSBACK | WAITASEC | ANNOYME | EMERGENCY | CHANGEME | REMOTE | KILL | INIT | STOP | RESTARTME]"
		exit 1
		;;
esac
exit 0
