#!/sbin/sh
#
# powerfail	This script is run when the UPS tells the system
#		the power has gone. Tell everybody, sync the disks
#		and drop into single user mode as fast as possible.
#		This script is also being run when the power comes
#		up again (if it does in time!)
#
# Version:	@(#) /etc/powerfail 1.01 26-Oct-1993
#
# Author:	Miquel van Smoorenburg, <miquels@drinkel.nl.mugnet.org>
#

  # Source function library.
  . /sbin/init.d/functions

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

  # See what happened.
  case "$1" in
    start)
	# Tell everybody.
	wall "THE POWER IS DOWN! SHUTTING DOWN SYSTEM!"

	[ -f /sbin/init.d/network ] && {
	    echo "Stopping NETWORK services.."
	    /sbin/init.d/network stop
	}

	[ -f /sbin/init.d/inetd ] && {
	    echo "Stopping INET services.."
	    /sbin/init.d/inetd stop
	}

	[ -f /sbin/init.d/sendmail ] && {
	    echo "Stopping MAIL services.."
	    /sbin/init.d/sendmail stop
	}

	[ -f /sbin/init.d/nfs ] && {
	    echo "Stopping NFS services.."
	    /sbin/init.d/nfs stop
	}

	[ -f /sbin/init.d/ether ] && {
	    echo "Stopping ETHER services.."
	    /sbin/init.d/ether stop
	}

	# Don't allow users to login.
	echo "POWER FAILURE" > /etc/nologin

	# Tell init to go single user.
	trap "" SIGTERM
	init -t5 S

	# Sync disks and go single user.
	# Pray no process writes to disk anymore..
	sync ; sleep 4 ; sync

	exit 0
	;;
  stop)
	# Ok, power is good again. Say so on the console.
	echo "THE POWER IS BACK, GOING MULTI USER"

	# If we're not single user don't try to restore.
	set `runlevel` > /dev/null
	if [ "$1" != S ]
	then
		exit 0
	fi

	# Go back to previous runlevel.
	init $2 2> /dev/null

	# And allow users to log in.
	rm -f /etc/nologin
	;;
  *)
	echo "Usage: /sbin/init.d/powerfail {start|stop}"
	exit 1
	;;
  esac

exit 0
