#!/bin/sh
#
# bpowerfail	This is a script run by init after a power event from
#		bpowerd is registered.  It should schedule and cancel 
#		shutdowns with appropriate delays for the nature of the
#		event.
#
#		This is adapted by Christopher Craig <ccraig@cc.gatech.edu>
#		from Tom Webster's genpowerfail
#

PATH=/sbin:/etc:/bin:/usr/bin:/usr/sbin

#set the location of the upsstatus file
statusfile="/var/run/upsstatus"

# set the location of the file containing shutdown pids
pidfile="/var/run/shutdown.pid"

# determine event type
case "$1" in
    start)
	# powerfail
	if [ -f $pidfile ]
	then
	    # kill running shutdowns
	    shutdown -c "Halting shutdown to process power event..."
	fi
	
	# determine level of failure
	if [ -r $statusfile ]
	then
	    failtype=`head -1 $statusfile`
	    case "$failtype" in
		FAIL)  # powerfail, battery is fine
		    shutdown -h +15 "THE POWER IS DOWN! SHUTTING DOWN SYSTEM!" </dev/console &
		    ;;
		SCRAM) # powerfail, battery is low
		    shutdown -h now "THE POWER IS DOWN! BATTERY LOW! SHUTTING DOWN SYSTEM NOW!" </dev/console &
		    ;;
		CABLE) # powerfail on startup, bad cable
		    shutdown -h +6 "BAD CABLE! SHUTTING DOWN SYSTEM!" </dev/console &
		    ;;
		ERROR) # bpowerd reported an error
		    shutdown -h +6 "ERROR IN UPS PROGRAM! SHUTTING DOWN SYSTEM!" </dev/console &
		    ;;
		*) # unknown error, assume power down
		    shutdown -h +15 "THE POWER IS DOWN! SHUTTING DOWN SYSTEM!" </dev/console &
		    ;;
	    esac
	else
	    # upsstatus doesn't exist, assume some other UPS program has 
	    # detected a shutdown.
	    shutdown -h +15 "THE POWER IS DOWN! SHUTTING DOWN SYSTEM!" </dev/console &
	fi
	;;

    stop) # Power has returned
	shutdown -c "THE POWER IS BACK"
	;;

    *)  # Somebody doesn't know what they're doing
	echo "This program should only be run by init."
	echo "Usage: /etc/rc.d/bpowerfail {start|stop}"
	exit 1
	;;
esac;
exit 0
