#!/bin/bash
#
# ::copy::
# ::maintainer::
#
# ::do_not_edit::
#
# v.1.1 2021.09.13
#
exec >/var/log/cron.timesync 2>&1	# not appended, overwrite


# "records" actual timestamp
[ -d /var/lib/initscripts ] || mkdir /var/lib/initscripts || :
[ -d /var/lib/initscripts ] && {
	:> /var/lib/initscripts/last-timestamp
}

[ -f /etc/default/kusa-services ] || {
	echo "no /etc/default/kusa-services, exit"
	exit 0
}

. /etc/default/kusa-services

[ "$KUSA_SERVICE_RDATE" == "" ] && exit 0

max_diff="300"


remote=$(rdate -p $KUSA_SERVICE_RDATE) || exit 0
remotesecs=$(date '+%s' --date "$remote")

local=$(date)
localsecs=$(date '+%s')

if [ $remotesecs -lt $localsecs ]
then
	diff=$(expr $localsecs - $remotesecs)
else
	diff=$(expr $remotesecs - $localsecs)
fi

echo "D> local=$local ($localsecs) remote=$remote ($remotesecs) diff=$diff"

if [ $diff -gt $max_diff ]
then
	logger -t "KUSA_TIME" "diff>$max_diff, forcing update (local=$local, remote=$remote)"
	rdate -s $KUSA_SERVICE_RDATE
	[ -f /etc/init.d/ntp ] && sh /etc/init.d/ntp restart
fi


exit 0
