#!/bin/bash
# Name: ntpdate  
# Date: 2006-07-24 10:40
# Author: MontaVista Software, Inc. <source@mvista.com>
# Copyright: Copyright 1999-2003 MontaVista Software, Inc.
# License: 2003 (c) MontaVista Software, Inc. This file is licensed
#          under the terms of the GNU General Public License version 2.
#          This program is licensed "as is" without any warranty of any
#          kind, whether express or implied.
#
# Copyright 2002, 2003, 2004 Sony Corporation
# Copyright 2002, 2003, 2004 Matsushita Electric Industrial Co., Ltd.
#
### BEGIN INIT INFO
# Required-Start: 
# Required-Stop:
# Should-Start:
# Should-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: start/stop ntpdate daemon
# Description: set the local machine time from remote machines running NTP.
### END INIT INFO 
#

test -f /usr/sbin/ntpdate || exit 0
test -f /etc/default/ntpdate || exit 0

. /etc/default/ntpdate

test -n "$NTPSERVERS" || exit 0

# ntpdate resolves servers serially, which can amount to a very long timeout
# when DNS servers are unreachable or other trouble that introduces delays
# in name resolving.
# This function replaces all entries in NTPSERVERS by the IPv4 and IPv6 addresses
# using getent, if present, resolving all names in parallel. If getent is not
# available then no resolving is done. Any IPv4 and IPv6 addresses in NTPSERVERS
# are preserved but order can be changed.  
resolve_servers() {
     local s t results

     type getent > /dev/null 2>/dev/null || return
     type awk > /dev/null 2>/dev/null || return

     results=
     for s in $NTPSERVERS; do
	 t=$(mktemp -t ntpdateXXXXXX)
	 [ -f "$t" ] || continue
	 getent ahosts "$s" > "$t" || echo failed resolving "$s" >&2 &
	 results="$t $results"
     done
     if [ -n "$results" ]; then
         wait
         NTPSERVERS="$(awk '$2 == "DGRAM" {addrs[$1] = $1}; END { for (a in addrs) print addrs[a] }' $results)"
         rm -f $results
     fi
}

case "$1" in
    start|force-reload)
	echo -n "Running ntpdate to synchronize clock"
	resolve_servers
	/usr/sbin/ntpdate -u -b -s $NTPSERVERS
	echo "."
	;;
    restart|reload)
	# Drop -b to slew clock rather than step it if called after system is up
	echo -n "Running ntpdate to synchronize clock"
	resolve_servers
	/usr/sbin/ntpdate -u -s $NTPSERVERS
	echo "."
	;;
    stop)
	;;
    *)
	echo "Usage: /etc/init.d/ntpdate {start|stop|restart|reload|force-reload}"
	exit 1
esac

exit 0
