#! /bin/sh

# Check to see if the system date is in the past, relative to the build time
# of the system, or way in the future (2039).  The build time is set when
# the image is created, not when the binary image is installed or updated.
# Checking the time of a file that is update by 'apt-get ugprade'
# won't work, because that could be done when the system clock is
# incorrect

# Note that image-release does not change on an apt-get upgrade.

# This script always exits with 0 so it won't show up as a boot
# time failure

checkfile=/etc/image-release
sanitylowdate=1456790400  # 2016-03-01 midnight, before 3.0.0
sanityhighdate=2187820800 # 2039-05-01 midnight

prog=${0##*/}

fail()
{
   echo "${prog}: $@"
   exit 0
}

# this runs before syslog, so it will only be on console and in journal
[ -e $checkfile ] ||
   fail Unable to check system date correctness, $checkfile missing

curdate=$(date +%s 2>&1)
case "$curdate" in
''|*[!0-9]*) fail Invalid current time \""$curdate"\", not checking ;;
esac

# check for the file being present, and having a somewhat sane date
# before using it.
builddate="$(stat --printf=%Y $checkfile 2>&1)"
# verify we got a number back, or numeric test below will get syntax error
case "$builddate" in
''|*[!0-9]*) fail Invalid date \""$builddate"\" from $checkfile ;;
esac

[ $builddate -lt $sanitylowdate -o $builddate -gt $sanityhighdate ] &&
    fail Not checking system date, $checkfile date "$builddate" not reasonable

# if date is "reasonable", do nothing
[ $builddate -lt $curdate -a $curdate -lt $sanityhighdate ] && exit 0

# time is in past, set it to the the build date, and update the
# the hardware clock

humanbuilddate="$(date --iso-8601=seconds --date=@$builddate)"
humancurdate="$(date --iso-8601=seconds --date=@$curdate)"

if [ $builddate -ge $curdate ]; then
   state="earlier than build date"
else
   state="too far in future"
fi

echo ${prog}: "Date $humancurdate is $state"
echo ${prog}: Changing system date to build date "$humanbuilddate"

date --set @$builddate ||
    fail "Unable to set date to $builddate, $humanbuilddate"

hwclock --systohc ||
    fail "Unable to set hardware clock to system date $humanbuilddate"
