#!/bin/bash2
#
# ctrltime (c) phion IT GmbH 2001-2007
#		  (c) phion AG 2007-2009
#
# KmgVersionString 5.0.0.2

BOXINFO="/opt/phion/bin/boxinfo"


STARTNTP=0
UTC=0
BINDIP=0.0.0.0
STATUS=0

EVENTCLASSNAME=ctrltime
USER=$(whoami)

while getopts ":fnrub:U:" opt ; do
		case $opt in
	
		n)
			RESTARTNTP=1
			STARTNTP=1
			;;
		f  ) 
			STARTNTP=1
			;;
		r )
			STARTNTP=0
			;;
			
		b)
			BINDIP=${OPTARG:-0.0.0.0}
			;;
		u  ) 	
		 	UTC=1
			;;
		U) USER=${OPTARG}
			;;

		\? ) echo $0 -n or -r or -f [-u] -b bind_ip ntp_server_ips
			 exit 1
		esac

done

shift $((OPTIND - 1))


PMODPATH="/opt/phion/modules/box/boxadm"
[ -f ${PMODPATH}/moddefs.conf ] && source ${PMODPATH}/moddefs.conf  
MYLOGFLE="${logfilectrltime:-"box_Settings_time"}"

if [ -f /etc/phion/functions ]; then
	 source /etc/phion/functions
	 logerror="LogError $MYLOGFLE"
else
	exit 1
fi

LOGGER=/bin/logger

[ ! -x $LOGGER ] && [ -x /usr/bin/logger ] && LOGGER=/usr/bin/logger



ARGLIST="$@"


$logerror "Info" "[0051060] control: ----------------- START time modification (ctrltime util) -----------------------"
if [[ ${RESTARTNTP:-0} = 1  ]]; then
	$logerror "Info" "[0051061] control: restarting NTP time server"
	
	MYSTARTNTP=$(${BOXINFO} config /opt/phion/config/active/boxadm.conf / startntp 2>/dev/null)
	
	[[ ${MYSTARTNTP:-n} = n ]] && {
		$logerror "Error" "[0051061] control: NTP server is not meant to run, exiting"
		$logerror "Info" "[0051063] control: ------------------ END time modification (ctrltime util) ------------------------"	
		exit 1
	}
	
	MYSYNC=$(${BOXINFO} config /opt/phion/config/active/boxadm.conf / sync 2>/dev/null)
	
	[[ ${MYSYNC:-n} = y ]] && {
		MYSYNCIPS=$(${BOXINFO} config /opt/phion/config/active/boxadm.conf / tmaster 2>/dev/null)
		[[ _"${MYSYNCIPS}" = _ ]] && MYSYNC=n
	}
	
else
	$logerror "Info" "[0051061] control: attempt synchronization with NTP time server ip $ARGLIST"

	[ _"${ARGLIST}" = _ ] && {
		$logerror "Error" "[0051062] control->1: no time server ip specified, terminating"
		$logerror "Info" "[0051063] control: ------------------ END time modification (ctrltime util) ------------------------"	
		exit 1
	}
fi

[ -x /etc/rc.d/init.d/ntpd  ] && {

	/etc/rc.d/init.d/ntpd stop &>/dev/null

	if [ $? -eq 0 ]; then
		$logerror "Info" "[0051035] control: shutdown of NTP daemon succeeded"
	else
		$logerror "Error" "[0051035] control: shutdown of NTP daemon failed"
	fi

	#paranoia measures:

	/usr/bin/killall -q -TERM ntpd 
	sleep 1 	
}

NTPDATEOK=N

[ -x /usr/sbin/ntpdate -a ${RESTARTNTP:-0} != 1 ] && {
	for i in $ARGLIST; do

		DATEBEFORE=$(date +%Y-%m-%d:%H:%M:%S)
  		NTPRES=$(/usr/sbin/ntpdate -4 -t3 -b -A $BINDIP  "$i" 2>&1 ) 
		RET=$?
		DATEAFTER=$(date +%Y-%m-%d:%H:%M:%S)
		set -- $NTPRES
		NTPPROC=${6%:}
		shift 6
	  	if  [ $RET -eq 0 ]; then 
			NTPDATEOK=Y
			# $i server, $BINDIP
			$logerror "Info" "[0051037] control: Admin ${USER} triggered NTP sync from ${i}: $*."
			$logerror "Info" "[0051038] control: Time before sync ${DATEBEFORE}, time after sync ${DATEAFTER}"
			$LOGGER -i -puucp.info -tEvent "layer_id=2;layer_name=control;class_id=1;class_name=${EVENTCLASSNAME};type_id=2081;type_name=${NTPPROC};data=$*"
			break
		elif [ $RET -eq 2 ]; then	#option not understood
			SYNCIP=""
			DATEBEFORE=$(date +%Y-%m-%d:%H:%M:%S)
			NTPRES=$(/usr/sbin/ntpdate -4 -t3 -b  "$i" 2>&1 )  
			RET=$?
			DATEAFTER=$(date +%Y-%m-%d:%H:%M:%S)
			set -- $NTPRES
			NTPPROC=${6%:}
			shift 6
			if  [ $RET -eq 0 ]; then 
				NTPDATEOK=Y
				$logerror "Info" "[0051037] control: Admin ${USER} triggered NTP sync from ${i}: $*."
				$logerror "Info" "[0051038] control: Time before sync ${DATEBEFORE}, time after sync ${DATEAFTER}"
				$LOGGER -i -puucp.info -tEvent "layer_id=2;layer_name=control;class_id=1;class_name=${EVENTCLASSNAME};type_id=2081;type_name=${NTPPROC};data=$*"
				break
			else
				$logerror "Warning" "[0051037] control: Admin ${USER} triggered NTP sync from $i failed!"
			fi
		else
			$logerror "Warning" "[0051037] control: Admin ${USER} triggered NTP sync from $i failed!"
		fi

	done
	
	if [ "$NTPDATEOK" = "Y" ]; then
		[ -x /sbin/hwclock ] && /sbin/hwclock --systohc --utc
		[ $? -eq 0 ] && $logerror "Info" "[0051041] control: hardware clock set to system time using UTC"
	else
		$logerror "Error" "[0051043] control: Admin ${USER} triggered NTP sync failed for all time servers"
		$LOGGER -i -puucp.info -tEvent "layer_id=2;layer_name=control;class_id=1;class_name=${EVENTCLASSNAME};type_id=2080;type_name=ntpdate;data=ntpdate using bind IP $BINDIP failed for all time servers"
		let STATUS++
	fi

}

[ -x /etc/rc.d/init.d/ntpd ] && [ $STARTNTP = 1 ] && {

	  	/etc/rc.d/init.d/ntpd start &>/dev/null
		if [ $? -eq 0 ]; then
			$logerror "Info" "[0051044] control: start of NTP daemon succeeded"
			$LOGGER -i -puucp.info -tEvent "layer_id=2;layer_name=control;class_id=1;class_name=${EVENTCLASSNAME};type_id=2071;type_name=ntpd;data=restart of ntpd succeeded"  
		else
			$logerror "Error" "[0051044] control: start of NTP daemon failed"
			let STATUS++
			$LOGGER -i -puucp.info -tEvent "layer_id=2;layer_name=control;class_id=1;class_name=${EVENTCLASSNAME};type_id=2070;type_name=ntpd;data=startup of ntpd  failed" 
		fi
}


[  $STATUS != 0 ] && {
	$logerror "Error" "[0051064] control: failed to accomplish proper time synchronization (status ${STATUS}, local IP ${BINDIP})"
}

$logerror "Info" "[0051063] control: ------------------ END time modification (ctrltime util) ------------------------"

exit $STATUS

