#!/bin/sh

# First of all, run wr_date, so to fix tai_offset in the kernel
/wr/bin/wr_date get > /dev/null

F=/wr/etc/wr_date.conf

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

		# pick busybox ntpd explicitly, to avoid real ntpd instances
		echo "Setting host time using ntpd"
		busybox ntpd -n -q -p $S
		if [ $? == 0 ]; then
			# successful
			echo "Date set from $S"
			date_set=1
			echo "Setting WR time from host time"
			/wr/bin/wr_date set host
		fi
	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
