#!/bin/bash
# TrutzBox clock: ask the router for the time as soon as the UPLINK comes up
# (stage B of the clock concept v1.3: on every start and every
# new uplink). At boot trutzbox-time-bootstrap.service does the same; the
# script treats two events within 30 s as one and leaves a clock alone that
# NTS already keeps in sync, so this hook costs nothing on a healthy box.
#
# Only the uplink, as in 54-trutz-encrypted-dns: LAN ports, the bridge, wifi
# and tunnels coming up say nothing about the router.
INTERFACE="${1:-}"
ACTION="${2:-}"

case "$ACTION" in
    up|dhcp4-change|dhcp6-change|connectivity-change) ;;
    *) exit 0 ;;
esac

if [ -n "$INTERFACE" ]; then
    UPLINK=$(ip -4 route show default 2>/dev/null | awk '{ print $5; exit }')
    [ -n "$UPLINK" ] || UPLINK=$(ip -6 route show default 2>/dev/null | awk '{ for (i = 1; i < NF; i++) if ($i == "dev") { print $(i+1); exit } }')
    [ -n "$UPLINK" ] && [ "$INTERFACE" != "$UPLINK" ] && exit 0
    case "$INTERFACE" in
        lo|br0|tun*|veth*|wlp*|wlan*|wg*) exit 0 ;;
    esac
fi

# In sync means NTS leads, nothing to ask.
code=$(ntptime 2>/dev/null | sed -n 's/^ntp_gettime() returns code \([0-9]*\).*/\1/p')
[ -n "$code" ] && [ "$code" != 5 ] && exit 0

systemctl start --no-block trutzbox-time-wan.service 2>/dev/null || true
exit 0
