#!/usr/bin/sh

# Get the saved time (or empty) and clock time, in RFC399 format
# This format sorts lexicographically

CLOCKFILE="${CLOCKFILE:-/var/lib/soft-hwclock/soft-hwclock.data}"
CTIME=$(date --rfc-3339=seconds)
FTIME=$(test -f "${CLOCKFILE}" && cat "${CLOCKFILE}")

# if the file time is in the future, use that
setclock() {
	if expr "${FTIME}" \> "${CTIME}" >/dev/null ; then
		echo "loading saved time ${FTIME} over ${CTIME}"
		date --set="${FTIME}"
		#date --date="${FTIME}"
		#echo would set clock to $FTIME
	else
		echo "ignoring saved time ${FTIME} over ${CTIME}"
	fi
}


# if current time is greater than what is in the file, save it
saveclock() {
	if expr "${CTIME}" \> "${FTIME}" >/dev/null ; then
		echo "saving time ${CTIME} over ${FTIME}"
		echo "${CTIME}" > "${CLOCKFILE}"
	else
		echo "not saving time ${CTIME} over ${FTIME}"
	fi
}


case "$1" in
	load)
		setclock
		;;
	save)
		saveclock
		;;
	tick)
		saveclock
		;;
	*)
		echo "Usage: $0 {load|save|tick}"
		exit 1
		;;
esac

