#!/bin/bash
# Written by Markus Gaugusch <markus@gaugusch.at>
#
# Put the following in /etc/cron.d/ashutdown:
# -1-59/10 * * * * root /usr/local/bin/ashutdown checkonly
# -0-59/10 * * * * root /usr/local/bin/ashutdown
# This means, that at minute 01, 11, 21, ... all hosts are checked and
# at minute 00, 10, 20, ... the machine will be shutdown, if no hosts
# have been up before.

# list of hosts to check - CUSTOMIZE THIS!
HOSTS="192.168.0.2 192.168.0.3"

##### probably no changes needed below this line
PATH=$PATH:/usr/sbin:/sbin:/usr/bin:/usr/local/bin:/bin
LOGFILE=/var/log/ashutdown.log
LASTRUN=0
if [ -f /var/tmp/ashutdown.lastrun ] ; then
	LASTRUN=`cat /var/tmp/ashutdown.lastrun`
fi
THISRUN=`date +%s`
diff=$((THISRUN-LASTRUN))
echo $THISRUN > /var/tmp/ashutdown.lastrun

function cleanexit()
{
	echo `date +%c` cleanexit >> $LOGFILE
	if [ -f /tmp/doshutdown ] ; then
		rm -f /tmp/doshutdown
	fi
	exit 0
}

function doShutdown()
{
	rm /tmp/doshutdown
	/sbin/shutdown -h now
}

function checkHosts()
{
	for host in $HOSTS ; do
		if ping -w 2 -c 1 $host > /dev/null ; then
			cleanexit
		fi
	done
	if [ "`who | wc -l`" -gt 0 ] ; then
		echo "`who | wc -l` users logged in" >> $LOGFILE
		cleanexit
	fi
}

if [ "$1" = "force" ] ; then
	doShutdown
fi
if [ $diff -lt 120 -a -z "$1" ] ; then
	# echo "Last run was within two minutes, aborting"
	exit
fi

checkHosts

if [ "$1" = "checkonly" ] ; then
	sleep 5
	touch /tmp/doshutdown
	#echo -en "\r\nShutdown at `date "+%H:%M:%S" -d "now + 10 min"`">/dev/lcd
	echo `date +%c` shutdown in 10 min >>$LOGFILE
	exit 1
fi
if [ -f /tmp/doshutdown ] ; then
	doShutdown
fi
