#!/bin/sh
# Interlude script to set the time using time servers.
#

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

# If this isn't present then we are doomed...
#
[ -x /usr/sbin/ntpd ] || exit 1

# Do nothing when bringing up the loopback device
# We'll be called by via the if-up.d script directory
#
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

# At boot time we'll check whether the external Internet is reachable.
#
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
}

# Find out which NTP server to use....
# Historically this file could set NTPV4 to an NTP server,
#
[ -f /var/tmp/ntpv4.local ] && . /var/tmp/ntpv4.local

# Were we given one on the command -line? If so, use it
#
if [ -n "$1" ]; then                # Overrides everything
    NTPSERVER="$1"
elif [ -n "$NTPV4" ]; then          # ntpv4.local setting
    NTPSERVER="$NTPV4"
else                                # Any enigma2 setting?
    NTPSERVER="`awk -F= '$1 == "config.misc.NTPserver" {print $2; exit;}' /etc/enigma2/settings`"
    if [ -z "$NTPSERVER" ]; then
        NTPSERVER="pool.ntp.org"    # The default....
    fi
fi

# Interfaces are usually brought up during boot, but then we need to
# check that the Internet is reachable as well.
#
DELAY=""
if [ "$0" = "/etc/network/if-up.d/ntpdate-sync" ]; then
    DELAY="check_online"
fi

(
    $DELAY      # No-op if empty....
    if /usr/sbin/ntpd -nq -p $NTPSERVER 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
