#! /bin/sh
#
# genpowerfail	This script is run when the UPS tells the system
#		the power has gone. Tell everybody, ans start the 
#		shutdown based on the failure type.                
#		This script is also being run when the power comes
#		up again (if it does in time!)
#
# Version:	/etc/genpowerfail 1.0.1
#
# Author:	Tom Webster <webster@kaiwan.com>
#

# Set the path.
PATH=/sbin:/etc:/bin:/usr/bin

# Set location of upsstatus file
statpath="/etc/upsstatus"

# Set location of file containing PID of running shutdowns
spidpath="/etc/shutdownpid"

# See what happened.
case "$1" in
	start)
		# Called with a powerfail event, check to see if a shutdown is running, and stop it if it is.
		if [ -f $spidpath ]
		then
			# Shutdown is running, kill it to process the new event
			shutdown -c "Halting running shutdown to process power event...."
		fi

		# Get power problem and act on it
		if [ -r $statpath ]
		then
	                stats=`head -1 $statpath`
			case "$stats" in
				FAIL)  # Power is down
                                	shutdown -r +2 "THE POWER IS DOWN! SHUTTING DOWN SYSTEM! PLEASE LOG OFF NOW!" < /dev/console &
					;;
				SCRAM) # Battery is low
					shutdown -r now "THE POWER IS DOWN! BATTERY POWER IS LOW!  EMERGENCY SHUTDOWN!" < /dev/console &
					;;
				CABLE) # Possible bad cable
 	                                shutdown -r +1 "POSSIBLE BAD CABLE! SHUTTING DOWN SYSTEM! PLEASE LOG OFF NOW!" < /dev/console &
					;;
                                *)     # Unknown message, assume power is down
                                        shutdown -r +2 "THE POWER IS DOWN! SHUTTING DOWN SYSTEM! PLEASE LOG OFF NOW!" < /dev/console &
                                        ;;

			esac
		else
			# genowerfail called, and upsstatus dosen't exist.
			# Assume user is using powerd, and shutdown.
			shutdown -r +2 "THE POWER IS DOWN! SHUTTING DOWN SYSTEM! PLEASE LOG OFF NOW!" < /dev/console &
 
		fi
		;;
  	stop)
		# Ok, power is good again. Say so on the console.
		#echo "THE POWER IS BACK, GOING MULTI USER"

		shutdown -c "THE POWER IS BACK"
		;;
  	*)
		echo "Usage: /etc/genpowerfail {start|stop}"
		exit 1
		;;
  esac

  exit 0
