#!/bin/sh

NTPDRESTART=/var/run/ntpd-restart
NTPDBINDIP=/var/run/ntpd-ipaddr
NTPDOK=/var/run/ntpd-check-ok
NTPDCHECKLOCK=/var/lock/ntpd-check

NEEDRESTART=

if [ -e "$NTPDOK" -a "$1" != "--force" ]; then

    # ntpd was already checked as having resolved all its names, no
    # need to check again.

    exit 0

fi

# Avoid having two concurrent copies of this script running, as that
# could lead to two copies of ntpd running.

if ! dotlockfile -p -r 0 -l "$NTPDCHECKLOCK"; then

    # Another instance is already running and will take care of this

    exit 0

fi

# Recover the current IP address of non loopback interfaces
# and check if they differ, if they differ restart ntpd
# (this is required as ntpd locally binds to an address and is
# not capable of sending requests after the IP address changes)
IF_IPADDRS="$(ip -o -4 addr show  | sed -n -e '/^[0-9]\+:[[:space:]]*lo[[:space:]]/!{s/.*[[:space:]]\+inet[[:space:]]\+\([0-9.]\+\).*/\1/;p}')"
if [ -s "$NTPDBINDIP" ]; then
    NTPD_IPADDRS="$(< "$NTPDBINDIP")"
else
    NTPD_IPADDRS=
fi
if [ "$NTPD_IPADDRS" != "$IF_IPADDRS" ]; then
    echo -n "$IF_IPADDRS" > "$NTPDBINDIP"
    NEEDRESTART=yes
fi

# we check that the number of active peers of ntp is the same as that
# in the configuration file, if not there was a name lookup failure and
# we need to restart ntp
if [ -z "$NEEDRESTART" ]; then
    numlivepeers="$(ntpdc -n -c listpeers 2>/dev/null | wc -l)"
    numconfpeers="$(grep -c '^server' /etc/spinetix/spx-ntp.conf 2>/dev/null)"
    let numconfpeers=numconfpeers+1

    if [ "$numlivepeers" != "$numconfpeers" ]; then

	NEEDRESTART=yes

    fi
fi

if [ -n "$NEEDRESTART" ]; then

    [ -e "$NTPDOK" ] && rm -f "$NTPDOK"

    touch "$NTPDRESTART" # this file is for watchdog repair binary

    # NOTE: calling /etc/init.d/ntp restarts does not work reliably in
    # recent versions of the ntpd package
    pkill -0 -x ntpd && \
	/etc/init.d/ntp stop && \
	sleep 2 && \
	/etc/init.d/ntp start
else
    # ntpd is all ok, disable further automatic checks
    touch "$NTPDOK"

fi

dotlockfile -p -u "$NTPDCHECKLOCK"

exit 0
