#!/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

# We don't want more than one process running this at a time, so
# implement a simple mutex.
#
LOCKFILE=/var/lock/ntpdate
TFILE=$LOCKFILE.$$

touch $TFILE
ln $TFILE $LOCKFILE     # Try to make hard-link (atomic)
status=$?               # Remember the result
rm -f $TFILE            # Remove the per-process one

# If we failed to link it then it already exists. So we exit.
# Someone else got here 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

# This can be run at boot time from rc3.d (no arg), or from enigma2 (arg)
# Either way, we will set a 5s timeout for the attempt, which will catch
# any name-resolution or network access failures in one go.
#
# 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

# If we were called with a parameter, use it.
# We can set enigma2 to send its config.misc.NTPserver
#
if [ -n "$1" ]; then
    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`"
fi
[ -z "$NTPSERVER" ] && NTPSERVER="pool.ntp.org" # The fall-back....

# Now do the work - allow 5 seconds, kill after 7 seconds, if still there.
#
if timeout -k 7 5 /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

# 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
