#!/bin/bash

# Time-stamp: <2021-02-06 14:48 charles 60ntp>

# A script to get the DHCP option for ntp servers into the system and
# hand it to systemd-timesyncd (not ntp). Adapted from
# https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=537358#37.

# This script resides in /etc/NetworkManager/dispatcher.d, is owned
# by root:root, and should have permissions of 0744.

# Note that this script only handles IPV4.

# Note that this script creates and logs to its own log file. Once you
# are satisfied that it works, you can comment out the rest of the
# debug statements.

LOG=/var/log/NetworkManager

TSC=/etc/systemd/timesyncd.conf
GOLDENTSC=/etc/systemd/timesyncd.conf.au

# The first thing to do is copy /etc/systemd/timesyncd.conf to
# /etc/systemd/timesyncd.conf.au if it isn't already there.

if [ ! -e $GOLDENTSC ]; then
    cp -p $TSC $GOLDENTSC
    chmod a-wx $GOLDENTSC
fi

# /bin/echo Running 60ntp >> $LOG
/bin/echo "$# arguments: |$*|" >> $LOG

if [ -z "$1" ]; then
    # /bin/echo "$0: called with no interface" >> $LOG
    # /bin/echo Leaving 60ntp >> $LOG
    exit 0;
fi

ntp_server_restart() {
    systemctl restart systemd-timesyncd >> $LOG
}

ntp_servers_setup_remove() {
    echo "Removing any local NTP servers." >> $LOG
    cp -rp ${GOLDENTSC} ${TSC}
    ntp_server_restart
}

# Run the right scripts
case "$2" in
    up|vpn-up)

        /bin/echo "\$DHCP4_NTP_SERVERS is |$DHCP4_NTP_SERVERS|" >> $LOG

	if [ -z "$DHCP4_NTP_SERVERS" ]; then
            # we have no ntp server via DHCP, so we revert to the
            # fallback servers.
            /bin/echo "Removing any old NTP servers." >> $LOG
	    ntp_servers_setup_remove
	    exit 0;
	fi

        # I'm not sure you need this loop; it depends on what exactly
        # is in the variable $DHCP4_NTP_SERVERS. I haven't
        # experimented with it.
        TIMESERVERS='';
        for server in $DHCP4_NTP_SERVERS; do
            TIMESERVERS="$TIMESERVERS$server ";
        done

        /bin/echo "New time servers are |$TIMESERVERS|" >>$LOG

        sed -e "s/#NTP=/NTP=$TIMESERVERS/g" ${GOLDENTSC} > ${TSC}

        ntp_server_restart

        # /bin/echo Leaving 60ntp >> $LOG
        exit 0;

	ntp_server_restart
	;;
    down|vpn-down)
        ntp_servers_setup_remove
	;;
    hostname|dhcp4-change|dhcp6-change)
        # Do nothing
	;;
    *)
	# /bin/echo "$0: called with unknown action \`$2'" >> $LOG
        # /bin/echo Leaving 60ntp >> $LOG
	exit 0
	;;
esac

# /bin/echo Leaving 60ntp >> $LOG

exit 0
