#!/bin/bash

# Check accessibility of ntp server
# set HWclock to ntp time

dnsok=0

. /tmp/cmdline

function msg () {
	echo "$@"
	logger -t checkntp "$@"
}

if dig ${NTPSERVER} +time=3 >/dev/null;then
    dnsok=1
fi


if [ -z "$1" ]; then
	
	if [ ! -z "${NTPSERVER}" -a ${dnsok} -eq 1 ]; then
		ntpdate -q ${NTPSERVER} >/dev/null 2>&1 && touch /tmp/ntp.available
	else
		if [ "${IP_DHCPMODE}" = "CLIENT" ]; then
			if ps -C ntpd -o args=| grep -q ntp.conf.dhcp;then
				# We got a server from dhcp
				conffile=$(ps -C ntpd -o args=| grep -o '\-c *[a-zA-Z/.]*'|cut -d ' ' -f 2)
				ntpserver=$(grep '^server ' ${conffile} | cut -d ' ' -f 2)
            	# Test accessibility
            	ntpdate -q ${ntpserver} >/dev/null 2>&1  &&  touch /tmp/ntp.available
            fi
        fi
    fi
    
else
	if which wdstop >/dev/null; then
		wdstop
	else
		msg "wdstop not found"
	fi
	
	if pgrep -x ntpd; then
		NTPrunning=1
		/etc/init.d/ntp stop
	fi

	rc=-1
	if [ ! -z "${NTPSERVER}"  -a ${dnsok} -eq 1 ]; then
		ntpdate ${NTPSERVER} >/dev/null 2>&1 && rc=0
	else
		if [ "${IP_DHCPMODE}" = "CLIENT" ]; then
			if ps -C ntpd -o args=| grep -q ntp.conf.dhcp;then
				# We got a server from dhcp
				conffile=$(ps -C ntpd -o args=| grep -o '\-c *[a-zA-Z/.]*'|cut -d ' ' -f 2)
				ntpserver=$(grep '^server ' ${conffile} | cut -d ' ' -f 2)
				ntpdate ${ntpserver} >/dev/null 2>&1 && rc=0
			fi
		fi
	fi

	if [ $rc -eq 0 ]; then
		hwclock -w --utc
		msg "Hwclock set"
	fi


	if [ ! -z "${NTPrunning}" ]; then
		/etc/init.d/ntp start
	fi
	
	if which wdstart >/dev/null; then
		wdstart
	else
		msg "wdstart not found"
	fi
	
fi

exit 0
