#!/bin/sh

# First of all, run 'wr_date set host tai', so to fix TAI offset in the kernel. Does not set the time
/wr/bin/wr_date set host tai > /dev/null

F=/etc/wr_date.conf
#CCS=/sys/bus/clocksource/devices/clocksource0/current_clocksource

#Each NTP attempts last around 10s
ntp_retries()
{
	S=$1
	N=$2

	for i in `seq $N` ; do # Manual retries
		if ntpd -n -q -p $S -d; then
			success=1
			echo "NTP success"
			return 0
		else
			echo "Retry $i/$N : NTP query failed, unable to contact server ($S)."
		fi
	done
	echo "ERROR: could not reach NTP server '$S' after $N retries"
	return 1
}

ntp_to_hwclk()
{
	S=$1
	ntp_ntries=1

# Get timing mode: Get it from dot-config ad wr_date is started before PPSi
	TM=`grep -e '^CONFIG_TIME_' /wr/etc/dot-config | sed 's/^CONFIG_TIME_\(.*\)[=].*/\1/'`
	
	if [ "$TM" == "GM" ] ; then  
		ntp_ntries=10
	fi
		
	#Request NTP server and set time to FPGA is okay
	if ntp_retries $S ${ntp_ntries}; then
		/wr/bin/wr_date -v set host
		date_set=1
	fi
}

date_set=0
# check whether there is config file
if [ -f $F ]; then
	# pick the first server, if any
	S=$(grep 'ntpserver' $F | sed 's/ntpserver//' | head -n 1)
	# check whether server found
	if [ -n "$S" ]; then
		ntp_to_hwclk "$S"
	fi
fi
# if ntp failed, try to restore date saved before last reboot
if [ $date_set = 0 ] && [ -f /update/saved_date ]; then
	#date is not accurate but no better idea.
	echo "Restore saved time"
	date -s `cat /update/saved_date`
	echo "Setting WR time from host time"
	/wr/bin/wr_date set host
fi
