#!/bin/sh
#Source: https://github.com/TruePositiveLab/fake-hwclock/tree/master under MIT license
#Modifications include:
#  - CLOCKFILE location
#  - Adding "fake-hwclock:" to echoes
#  - Changing date commands to work with busybox implementation
#
#MIT License
#
#Copyright (c) 2017 Kristján Valur Jónsson
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all
#copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#SOFTWARE.

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

CLOCKFILE="/home/admin/conf/.fake-hwclock.data"

if test -f "${CLOCKFILE}" ; then
    FTIME=$(cat "${CLOCKFILE}")
    FTIMESEC=$(cat "${CLOCKFILE}" | xargs date -u +%s -d)
else
    FTIME=0
    FTIMESEC=0
fi

#busybox on SC4 requires a very specific date format to set correctly
# must be in this format and can't have time zone, so we use UTC
CTIME=$(date -u +"%Y.%m.%d-%H:%M:%S")
#Need CTIMESEC for comparisons
CTIMESEC=$(date -u +%s)

# if the file time is in the future, use that
setclock() {
	#Use FTIMESEC for comparison, but FTIME to set the actual time
	if test "${FTIMESEC}" -ge "${CTIMESEC}" ; then
		echo "fake-hwclock: loading saved time ${FTIMESEC} over ${CTIMESEC}"
		date -u -s ${FTIME}
	else
		echo "fake-hwclock: ignoring saved time ${FTIMESEC} over ${CTIMESEC}"
	fi
}


# Unconditionally overwrite the file. This will allow NTP syncs to correct
#  invalid future dates.
saveclock() {
	echo "fake-hwclock: saving time ${CTIME} over ${FTIME}"
	echo "${CTIME}" > "${CLOCKFILE}"
}


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

