#!/bin/sh
#
# Configure time at WRS startup
#
# If called with a parameter "ppsi" and unable to get time from ntp,
# then the time is not set to the value stored at the last restart in
# /update/saved_date
# The set of time from the /update/saved_date file can happen only at the call
# of this script from rcS during the bootup.

dotConfig="/wr/etc/dot-config"
if [ -f $dotConfig ]; then
	# source dot-config
	. $dotConfig
else
	echo "$0 unable to source dot-config ($dotConfig)!"
fi

WRS_LOG=$CONFIG_WRS_LOG_OTHER

# If empty turn it to /dev/null
if [ -z $WRS_LOG ]; then
	WRS_LOG="/dev/null";
fi

if [ "$1" = "ppsi" ]; then
	# This script is called from the ppsi, all messagess will be passed to
	# the log output via PPSi.
	LOGPIPE=
elif echo "$WRS_LOG" | grep / > /dev/null; then
	# If a pathname, use it
	eval LOGPIPE=\" \> $WRS_LOG 2\>\&1 \";
elif [ "$WRS_LOG" == "default_syslog" ]; then
	# Not a pathname: use verbatim
	eval LOGPIPE=\" 2\>\&1 \| logger -s -t wr_date --prio-prefix -p daemon.info\"
else
	# Not a pathname: use verbatim
	eval LOGPIPE=\" 2\>\&1 \| logger -s -t wr_date -p $WRS_LOG\"
fi

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

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
		eval ntpd -n -q -p $S -d $LOGPIPE
		if [ $? -eq 0 ]; then
			success=1
			eval echo "NTP success" $LOGPIPE
			return 0
		else
			eval echo "Retry $i/$N : NTP query failed, unable to contact server ($S)." $LOGPIPE
		fi
	done
	eval echo "ERROR: could not reach NTP server '$S' after $N retries" $LOGPIPE
	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
		eval /wr/bin/wr_date -v set host $LOGPIPE
		date_set=1
	fi
}

date_set=0
# Check whether there is the 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 and not called from PPSi try to restore the date information
# saved before the last reboot
if [ "$1" != "ppsi" ] && [ $date_set = 0 ] && [ -f /update/saved_date ]; then
	#date is not accurate but no better idea.
	eval echo "Restore saved time" $LOGPIPE
	date -s `cat /update/saved_date`
	eval echo "Setting WR time from host time" $LOGPIPE
	eval /wr/bin/wr_date set host $LOGPIPE
fi
