#!/bin/bash
### BEGIN INIT INFO
# Provides:          tgntpdate
# Required-Start:    $network $syslog
# Required-Stop:     $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# X-Start-Before:    ntp ntpsec inetd squid3
# Short-Description: Start and stop tgntpdate
# Description:       m-privacy: call ntpdate once at boot
### END INIT INFO

PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin

case "$1" in
  start)
	CONF=
	if test -f /etc/ntpsec/ntp.conf
	then
		CONF=/etc/ntpsec/ntp.conf
	fi
	if test -f /etc/ntp.conf
	then
		CONF="$CONF /etc/ntp.conf"
	fi
	if test -z "$CONF"
	then
		echo "No ntp.conf for tgntpdate found"
		exit 1
	fi
	NTPSERVERS="$(grep '^server' $CONF|grep -v '127.127.1.0\|debian.pool.ntp.org'|cut -d ' ' -f 2|sort -u -V|tr '\n' ' ')"
	if test -n "$NTPSERVERS"
	then
		echo "Running ntpdate -b $NTPSERVERS"
		if ! ntpdate -b $NTPSERVERS
		then
			echo "ntpdate failed, retrying after 10s"
			sleep 10
			if ! ntpdate -b $NTPSERVERS
			then
				echo "ntpdate failed twice, giving up"
			fi
		fi
	else
		echo "No usable NTP server for tgntpdate found"
	fi
	;;
  stop)
	;;
  force-reload|restart)
	$0 start
	;;
  *)
	echo "Usage: /etc/init.d/tgntpdate {start|stop|restart|force-reload}"
	exit 1
esac

exit 0
