#! /bin/sh
##
## \brief  Get the date from a NTP server and maintain the RTC.
##
## \author Christophe Blaess <cpb@logilin.fr>.
##
## \copyright 2020 Logilin.
##


## \brief  The NTP server address.
NTP_SERVER=pool.ntp.org

## \brief The default initial date when everything else has failed.
DEFAULT_DATE=040107002020

## \brief  The delay (in seconds) to retry joining the NTP server after a failure.
## Default: 2 minutes.
RETRY_AFTER_FAILURE_DELAY=120

## \brief  The delay (in seconds) to retry joining the NTP server after a successfull clock update.
## Default: 15 minutes.
RETRY_AFTER_SUCCESS_DELAY=900



update_date_from_ntp_server()
{
	if ping -c1 -w1 "${NTP_SERVER}" >/dev/null 2>&1
	then
		if ntpd -n -q -p "${NTP_SERVER}" >/dev/null 2>&1
		then
			return 0
		fi
	fi
	return 1
}



while true
do
	wait_delay=${RETRY_AFTER_FAILURE_DELAY}

	if update_date_from_ntp_server
	then
		wait_delay=${RETRY_AFTER_SUCCESS_DELAY}
	fi

	sleep ${wait_delay}
done
