#!/bin/sh
#
# tacitus	- keep the time on systems without RTC
#		  as close to actual as possible; ntpd
#		  would do the rest
#
# chkconfig: 2345 01 50
# description: set last known time on systems without RTC

timestampfile="/var/lib/last.known.time"

case "$1" in
	start)
		# try to set time
		# does the file exist and have any data?
		test -f "$timestampfile" -a -s "$timestampfile" \
		|| exit 0
		# does it contain valid timestamp?
		head -1 < "$timestampfile" \
		| egrep -q '^[0-9]{4}-[01][0-9]-[0123][0-9] [012][0-9]:[0-5][0-9]:[0-5][0-9][+-][01][0-9]:[0-9]{2}$' \
		|| exit 0
		# is the RTC behind of that time?
		test `date '+%s'` -gt `date -f "$timestampfile" '+%s'` \
		&& exit 0
		# ok, set the time to saved value
		date -s "`head -1 $timestampfile`"
		exit 0
		;;
	stop|restart|reload)
		# save time; file may normally be readable by everyone
		umask 022
		date --rfc-3339=seconds > "$timestampfile"
		exit 0
		;;
	status)
		echo Current time: `date --rfc-3339=seconds`
		test -f "$timestampfile" -a -s "$timestampfile" \
		|| exit 0
		head -1 < "$timestampfile" \
		| egrep -q '^[0-9]{4}-[01][0-9]-[0123][0-9] [012][0-9]:[0-5][0-9]:[0-5][0-9][+-][01][0-9]:[0-9]{2}$' \
		|| exit 0
		echo Saved time: `head -1 < "$timestampfile"`
		;;
	*)
		echo Usage:
		echo "$0 start"
		echo " - set time (on boot) to previously saved value"
		echo "$0 stop|restart|reload"
		echo " - save current time (on shutdown) for later use"
		echo "$0 status"
		echo " - show current and (if file exists) saved time"
		exit 1
esac
