#!/bin/bash
# TrutzBox encrypted DNS — re-check DoT as soon as the UPLINK comes up.
#
# The boot guard and the 4-hour timer may run while the WAN has no address
# yet; encrypted-dns.sh then leaves everything alone (reason "offline").
# Without this hook a box that boots before its router is ready would stay
# in plaintext until the next timer run.
#
# Only the uplink is of interest. Measured on both boxes 09.09.2026: without
# the checks below every LAN port coming up (enp3s0/enp4s0) and every
# connectivity-change — NetworkManager passes an EMPTY interface name for
# those — started the service, ten times in the first minute after a boot.
# Each run costs a service start and a DNS probe for nothing.
INTERFACE="${1:-}"
ACTION="${2:-}"

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

# The uplink is whatever carries the default route. An empty name comes from
# connectivity-change and is allowed through: that event has no interface but
# is exactly the moment the box learns it is online again.
if [ -n "$INTERFACE" ]; then
    UPLINK=$(ip -4 route show default 2>/dev/null | awk '{ print $5; exit }')
    [ -n "$UPLINK" ] && [ "$INTERFACE" != "$UPLINK" ] && exit 0
    case "$INTERFACE" in
        lo|br0|tun*|veth*|wlp*|wlan*) exit 0 ;;
    esac
fi

# Nothing to do while the chain is known-good: `auto` would only re-probe.
STATE=/var/lib/trutzbox/encrypted-dns-state
if [ "$(sed -n 's/^mode=//p' "$STATE" 2>/dev/null)" = "encrypted" ] \
        && [ "$(sed -n 's/^reason=//p' "$STATE" 2>/dev/null)" = "ok" ]; then
    exit 0
fi

logger -t trutz-encrypted-dns -- "uplink ${INTERFACE:-(connectivity)}: ${ACTION} — re-checking encrypted DNS"
systemctl start --no-block trutz-encrypted-dns-default.service 2>/dev/null || true
exit 0
