#!/bin/sh
### BEGIN INIT INFO
# Provides:          system-valid-time
# Required-Start:    $local_fs mountvirtfs
# Required-Stop:     $local_fs
# Default-Start:     S
# Default-Stop:      0 6
# Short-Description: Determines whether the system time is valid.
### END INIT INFO

. /etc/default/rcS

#
# This script is run after bootmisc, which initializes system time
# to the contents of /etc/timestamp (i. e. build time), if it is
# more recent than the currently set time. So, at this point,
# the lowest time that can be set is the /etc/timestamp time.
#
# Also, we may actually have a valid time (if board was reset
# without powering down), because the on-chip RTC is still
# running. In that case, the actual time will differ by a "big"
# amount from what is stored in /etc/timestamp. We can then
# propagate this information to StreamSDK, so it doesn't have to
# synchronize time (which implies waiting for network) and can
# faster pronounce that we have a valid system time.
#

if [ -e /etc/timestamp ]; then
	# work with UTC UNIX timestamps
	SYSTEMDATE=`date -u +%s`

	# use date to convert build "timestamp" to a UNIX timestamp
	read T < /etc/timestamp
	TIMESTAMP=`date -u +%s -d "${T:0:4}-${T:4:2}-${T:6:2} ${T:8:2}:${T:10:2}:${T:12:2}"`

	# if SYSTEMDATE is at least 60 seconds ahead of TIMESTAMP, consider it a valid time
	if [ $(( $SYSTEMDATE - 60 )) -gt "$TIMESTAMP" ]; then
		# indicate that the system time is valid after boot
		touch "/tmp/system-time-is-valid"
	fi
else
	echo "Timestamp file is not present!"
fi
