#!/bin/sh

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

test -x /usr/sbin/ntpdate || exit 0

if test -f /etc/default/ntpdate ; then
. /etc/default/ntpdate
fi

if test -f /var/tmp/ntpv4.local ; then
. /var/tmp/ntpv4.local
fi

check_online() {
	count=0
	while [ $count -lt 5 ]; do
		if ping -4 -c 1 www.google.com >/dev/null 2>&1 || ping -6 -c 1 www.google.com >/dev/null 2>&1; then
			break
		fi
		count=$((count+1))
	done
}

if [ "$NTPV4" != "" ]; then
	NTPSERVERS=$NTPV4
fi

if [ "$NTPSERVERS" = "" ] ; then
	if [ "$METHOD" = "" -a "$1" != "silent" ] ; then
		echo "Please set NTPSERVERS in /etc/default/ntpdate"
		exit 1
	else
		exit 0
	fi
fi

DELAY=""

# This is a heuristic: Interfaces are usually brought up during boot, so this is
# the right time to quickly step to the right time, rather than slewing to it.
if [ "$0" = "/etc/network/if-up.d/ntpdate-sync" ]; then
	DELAY="check_online"
	OPTS="-b"
fi

if [ "$METHOD" = loopback ]; then
	exit 0
fi

(

LOCKFILE=/var/lock/ntpdate

# Avoid running more than one at a time
if [ -x /usr/bin/lockfile-create ]; then
	lockfile-create $LOCKFILE
	lockfile-touch $LOCKFILE &
	LOCKTOUCHPID="$!"
fi

$DELAY

if /usr/sbin/ntpdate -s $OPTS $NTPSERVERS 2>/dev/null; then
	if [ "$UPDATE_HWCLOCK" = "yes" ] && [ -x /sbin/stb-hwclock ]; then
		/sbin/stb-hwclock --systohc || :
	fi
fi

if [ -x /usr/bin/lockfile-create ] ; then
	kill $LOCKTOUCHPID
	lockfile-remove $LOCKFILE
fi

) &
