#!/bin/bash
#
#VERSION=6
#CHANGES="when no ntp server provided by dhcp, use pool.ntp.org as default"

BEROCONF=/usr/fallback/beroconf
PATH=/bin:/sbin:/usr/bin:/usr/sbin::/usr/local/bin:/usr/local/sbin:/usr/fallback
NTP_DEFAULT="pool.ntp.org"
# evaluate everything
if [[ "$(pidof isgw)" == '' ]] || [[ "$(query_isgw kt | grep 'TOTAL CALLS' | cut -d ':' -f 2)" = '0' ]]; then
	# when gui-ntphost set, ntphost will be from gui-ntphost value, DHCP or default
	NTP=$(${BEROCONF} get root ntphost | grep -v failed) 
	[ -z "${NTP}" ] && NTP=$(${BEROCONF} get root gui-ntphost | grep -v failed) 
	# if still empty, should not happen - try default ntp
	if [ -z "${NTP}" ]; then 
		# check default ntp server if available, as rdate would takes long time to timeout if fail
		if ! ping -s 1 -c 1 ${NTP_DEFAULT} &>/dev/null; then 
			exit 1 # if no dns configured or no internet connection, we cannot update time :(
		fi
		NTP=${NTP_DEFAULT}
	fi
	/usr/local/bin/rdate -ns ${NTP} &> /dev/null
fi

exit 0
