#! /bin/sh

EXEC="/usr/sbin/ntpd"
PIDFILE="/var/run/ntp.pid"
TICKADJEXEC="/usr/sbin/tickadj"

#
# ntpd	init.d script for ntpdc from ntp.isc.org
test -x $EXEC -a -r /etc/ntp.conf || exit 0
# rcS contains TICKADJ
test -r /etc/default/rcS && . /etc/default/rcS

# Functions to do individual actions
settick(){
  	# If TICKADJ is set we *must* adjust it before we start, because the
	# driftfile relies on the correct setting
	test -n "$TICKADJ" -a -x $TICKADJEXEC && {
		echo -n "Setting tick to $TICKADJ: "
		$TICKADJEXEC "$TICKADJ"
		echo "done"
	}
}
# Generate JMUConfig's default NTP configuration.
# We must do it here because JMUConfig is started later in the boot process
genconf(){
	NTPGEN="/usr/bin/jmuconfig-gen-ntp-conf.sh"
	grep -q "JMUConfig" /etc/ntp.conf || "${NTPGEN}" > /etc/ntp.conf
}
ntpsync(){
	SERVER=`grep ^server /etc/ntp.conf | head -n 1 | awk '{print $2}'`
	ntpdate -u -b "${SERVER}" && hwclock -u -w
}
startdaemon(){
	genconf
	echo -n "Starting ntpd: "
	start-stop-daemon --start -x $EXEC -- -p $PIDFILE "$@"
	echo "done"
}
stopdaemon(){
	echo -n "Stopping ntpd: "
	start-stop-daemon --stop -p $PIDFILE
	rm -f $PIDFILE
	echo "done"
}

case "$1" in
  start)

	# Run the script in background when called at boot
	CALLER=`cat /proc/$PPID/status | grep ^Name: | awk '{print $2}'`
	if [ "$CALLER" = "rc" ]; then
		(
		settick
		ntpsync
		startdaemon
		) &
	else
		settick
		ntpsync
		startdaemon
	fi

	;;
  stop)
  	stopdaemon
	;;
  force-sync)
	[ -e "$PIDFILE" ] && ntpsync
	;;
  force-reload)
  	stopdaemon
  	settick
	startdaemon
	;;
  restart|reload)
  	# Don't reset the tick here
	stopdaemon
	startdaemon
	;;
  *)
	echo "Usage: ntpd { start | stop | restart | reload }" >&2
	exit 1
	;;
esac

exit 0
