#!/bin/bash

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

dnsok=0

OSType=$(omgsysteminfo --val --filter=os.name)

if [ "$OSType" = "ubuntu" ]; then
    ntpcmd="/etc/init.d/ntp"
else
    ntpcmd="service ntpd"
fi

. /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
		${ntpcmd} stop
	fi

	rc=-1
	if [ ! -z "${NTPSERVER}"  -a ${dnsok} -eq 1 ]; then
		if ntpdate -q ${ntpserver} >/dev/null 2>&1; then
		  touch /tmp/ntp.available
		  ntpdate ${NTPSERVER} >/dev/null 2>&1
		  rc=0
		fi
	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)
				if ntpdate -q ${ntpserver} >/dev/null 2>&1; then
            		touch /tmp/ntp.available
					ntpdate ${ntpserver} >/dev/null 2>&1
					rc=0
				fi
			fi
		fi
	fi

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


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

exit 0
