#! /bin/sh
#
# Modified by:
#   Kjetil T. Homme <kjetilho@ifi.uio.no>
#   Peder Stray <peder@ifi.uio.no>
#
# Contributed under the terms of the GNU GPL v2 or later:
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or (at
# your option) any later version.
#
# Modified by Petter Reinholdtsen
#  - Restructure the code to move all site specific code into two
#    functions reboot_contact() and is_idle().
#  - Rewrote code to be easier to read.
#  - Rewrote to work with bourne shell, not only korn shell.
#  - Make sure to report unsupported operating systems before detaching.
#  - Ignore processes owned by user 'exim' as well.


# Return string with mail address to inform that the machine need a
# reboot, or empty string if this script can reboot the machine even
# if it isn't idle.
reboot_contact() {
	host=$1

	# This test only work for ifi.uio.no
	if innetgr -h $host sparcservers ; then
		echo "solaris-drift@ifi.uio.no"
	fi
}

# Return true if machine is idle, and false if it isn't
is_idle() {
	if [ "$(who)" ] ; then
		false
	else
		true
	fi
}

if pgrep -x -u root shutdown >/dev/null
then
	echo "warning: already running shutdown"
	exit 0
fi

# Check and report OS problems before detaching
case `uname -s` in
	SunOS)	shutdown=/usr/ucb/shutdown ;;
	Linux)	shutdown=/sbin/shutdown ;;
	*)	echo "error: unsupported operating system"
		exit 1
		;;
esac

if [ "$1" = "detached" ]; then
	shift
else
	exec /sbin/start-stop-daemon --start --background \
	    --exec $0 -- detached "$@"
fi

option="-r"
case $1 in
	-h)	option="-h"; shift ;;
esac

# reboot no later than 5 in the morning, at least 30 hour in the future
hnow=`date +%H`
time=`expr \( 53 - $hnow \) \* 60`

# start a shutdown in the background, unless reboot_contact is set
host=`uname -n`
mailto=`reboot_contact $host`
if [ "$mailto" ] ; then
	echo "Machine $host will be rebootet when idle!" |
	    mail -s "reboot-when-idle: $host" $mailto
else
	logger -t reboot-when-idle "info: will reboot host when idle, or in $time minutes"

	$shutdown $option +$time "$@" &
fi

count=0
until is_idle
do
	sleep 60
#	count=$((count+1))
#	if [ $count -gt 720 ]
#	then
#		case $(date +%H) in
#			2[1-3])	$shutdown $option +120 "$@" ;;
#		esac
#	fi
done

$shutdown -c

# here we need to sleep a bit.  shutdown send itself into the
# background, and use some time to stop the old one.
# 
# Broadcast message from root (Thu Sep  4 06:32:50 2003):
# 
# The system is going DOWN for reboot in 2820 minutes!
# + /sbin/shutdown -c
# + /sbin/shutdown -r now
# shutdown: already running.
# root@rovereto /var/log 17 # 
# Shutdown cancelled.

sleep 5

logger -t reboot-when-idle "info: rebooting idle host"

$shutdown $option now "$@"
