#!/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
        sleep 0.5
# No point in pinging by-name to test whether the network is up as that
# requires the network to be up to resolve the name!!
#   So instead ping a known DNS server address.
#   Possible ipv4/ipv6 choices (May 2022) are:
# Google:
#       8.8.8.8 or 2001:4860:4860::8888
# Quad9
#       9.9.9.9 or 2620:fe::fe:9
# Cloudfare
#       1.1.1.1 or 2606:4700:4700::1111
#
# Only send 1 packet (-c) and only wait for 3s (-W)
        if ping -4 -c 1 -W 3 8.8.8.8 >/dev/null 2>&1 ||
           ping -6 -c 1 -W 3 2001:4860:4860::8888 >/dev/null 2>&1; then
            return 0
        fi
        count=$((count+1))
    done
    exit 0
}

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"
# ntpdate OPTS (ONLY!)
    OPTS="-b -p1"   # -p1 - be as quick as possible at boot time
fi

# Do nothing when bringing up the loopback device
#
if [ "$METHOD" = loopback ]; then
    exit 0
fi

# Avoid running more than one at a time
#
LOCKFILE=/var/lock/ntpdate
TFILE=$LOCKFILE.$$

touch $TFILE
ln $TFILE $LOCKFILE
status=$?
rm -f $TFILE

# If we failed to link it then it already exists. So we exit.
# Someone else got there first.
#
[ $status -ne 0 ] && exit 0

# Ensure we'll remove the lock file when we exit
#
free_lock() {
    rm -f $LOCKFILE
}
trap free_lock 0

(
    $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
    exit 0
) &

# wait for all subprocesses to finish
# this is required when using systemd service as ntpd will start before ntpdate finishes
# and results in a bind error (port 123)
#
wait
