#!/bin/bash
# postinst script for Trutz-Network
#
# see: dh_installdeb(1)

set -e

# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <postinst> `abort-remove'
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package

# Helper script for performing file diversions
divert-file() {
    DIR_NAME=$1
    FILE_NAME=$2
    DIVERT_NAME=$3
    PKG=$4

    FILE=$DIR_NAME/$FILE_NAME
    DIVERT=$DIR_NAME/$DIVERT_NAME
    ORIG=$FILE_NAME".trutz-orig"

    echo "Begin diverting $FILE"

    # Make a copy of customized file
    cp $DIR_NAME/$DIVERT_NAME /tmp/$FILE_NAME

    # Remove any old diversion with a different name (idempotent)
    if dpkg-divert --list "$FILE" | grep -q "$ORIG"; then
        dpkg-divert --package "$PKG" --rename --remove "$FILE"
    fi

    # IMPORTANT:
    # Ensure the divert target does NOT exist yet
    if [ -e "$DIVERT" ] && ! dpkg-divert --list "$FILE" | grep -q "$DIVERT"; then
        rm -f "$DIVERT"
    fi

    # Add diversion (this creates /etc/hosts.trutz-network)
    dpkg-divert --package "$PKG" --rename --add --divert "$DIVERT" "$FILE"

    # Now install your replacement hosts file
    install -m 644 /tmp/$FILE_NAME $FILE
    echo "Diversion of $FILE complete"
}

case "$1" in
    configure)
    set -e
    
#   # Explicitly divert some files
#   divert-file "/etc" "hosts" "hosts.trutz-network" "trutz-network"
#   divert-file "/etc" "hosts.dnsmasg" "hosts.dnsmasq.trutz-network" "trutz-network"
#   divert-file "/etc" "nftables.conf" "nftables.conf.trutz-network" "trutz-network"


        # configure ip-processing via either 'iptables' or 'nftables' depending on Debian version

       DEBIAN_VERSION=$(lsb_release -a 2> /dev/null | grep "Codename" | awk '/Codename/ { print $2 }')
        echo "Running on $DEBIAN_VERSION"

        case $DEBIAN_VERSION in
            jessie | stretch )
        #       Decision: Do NOT change the running Jessie-32bit TrutzBox code
        #       Pre-Buster instances of Debian use 'iptables'
                ;;
            buster | bullseye | bookworm | trixie )
        #       Re-read nftables configuration


                BLOCKED_FILE="/etc/nftables.d/blocked_inet4.nft"
                BLOCKED_TEMPLATE="/usr/share/trutz-network/blocked_inet4.nft.dist"

                if [ ! -e "$BLOCKED_FILE" ]; then
                    install -D -m 0644 "$BLOCKED_TEMPLATE" "$BLOCKED_FILE"
                fi

                BLOCKED_FILE6="/etc/nftables.d/blocked_inet6.nft"
                BLOCKED_TEMPLATE6="/usr/share/trutz-network/blocked_inet6.nft.dist"

                if [ ! -e "$BLOCKED_FILE6" ]; then
                    install -D -m 0644 "$BLOCKED_TEMPLATE6" "$BLOCKED_FILE6"
                fi

                # Firewall exceptions (@allowed_inet4/6): the main conf includes
                # these files unconditionally, so they MUST exist before the
                # first reload — the backend fills them from its ip_allowed
                # table at runtime. Never overwrite an existing file: it holds
                # the admin's exceptions.
                ALLOWED_FILE="/etc/nftables.d/allowed_inet4.nft"
                ALLOWED_TEMPLATE="/usr/share/trutz-network/allowed_inet4.nft.dist"

                if [ ! -e "$ALLOWED_FILE" ]; then
                    install -D -m 0644 "$ALLOWED_TEMPLATE" "$ALLOWED_FILE"
                fi

                ALLOWED_FILE6="/etc/nftables.d/allowed_inet6.nft"
                ALLOWED_TEMPLATE6="/usr/share/trutz-network/allowed_inet6.nft.dist"

                if [ ! -e "$ALLOWED_FILE6" ]; then
                    install -D -m 0644 "$ALLOWED_TEMPLATE6" "$ALLOWED_FILE6"
                fi

                # Drop-in fuer die vom Admin eingetragenen Zeitserver. ntp.conf
                # bindet die Datei per `includefile` ein -- fehlt sie, startet ntpd
                # NICHT. Sie muss also immer existieren, auch wenn der Admin keine
                # eigenen Server gesetzt hat (dann ist sie nur ein Kommentarkopf).
                # Bestandsdatei nie ueberschreiben: sie traegt die Benutzereinstellung.
                NTP_CUSTOM_FILE="/etc/ntpsec/ntp.conf.d/custom.conf"
                NTP_CUSTOM_TEMPLATE="/usr/share/trutz-network/ntp-custom.conf.dist"

                if [ ! -e "$NTP_CUSTOM_FILE" ]; then
                    install -D -m 0644 "$NTP_CUSTOM_TEMPLATE" "$NTP_CUSTOM_FILE"
                fi

                # Zweites Drop-in: die EINGEBAUTEN NTS-Quellen (PTB/Netnod). Sie
                # stehen nicht mehr fest in ntp.conf, weil der Administrator sie in
                # der Oberfläche ersetzen darf -- dann schreibt das Backend die Datei
                # ohne Server-Zeilen. Bestandsdatei nie ueberschreiben (sie traegt
                # dann genau diese Wahl); fehlt sie, startet ntpd nicht.
                NTP_BUILTIN_FILE="/etc/ntpsec/ntp.conf.d/builtin.conf"
                NTP_BUILTIN_TEMPLATE="/usr/share/trutz-network/ntp-builtin.conf.dist"

                if [ ! -e "$NTP_BUILTIN_FILE" ]; then
                    install -D -m 0644 "$NTP_BUILTIN_TEMPLATE" "$NTP_BUILTIN_FILE"
                fi

                # Drittes Drop-in: der Rueckfall der Uhr (Konzept v1.3, Stufe F).
                # Leer, solange NTS geht; time-bootstrap.sh schreibt die PTB-Adressen
                # ohne nts hinein, wenn der Schluesseltausch von NTS im Netz gesperrt
                # ist, und leert sie wieder. Fehlt sie, startet ntpd nicht (preinst
                # legt sie schon vor dem Entpacken an). Bestand nie ueberschreiben.
                NTP_FALLBACK_FILE="/etc/ntpsec/ntp.conf.d/fallback.conf"
                if [ ! -e "$NTP_FALLBACK_FILE" ]; then
                    install -D -m 0644 /usr/share/trutz-network/ntp-fallback.conf.dist "$NTP_FALLBACK_FILE"
                fi

                DISCONNECTED_FILE="/etc/nftables.d/disconnected_macs.nft"
                DISCONNECTED_TEMPLATE="/usr/share/trutz-network/disconnected_macs.nft.dist"

                if [ ! -e "$DISCONNECTED_FILE" ]; then
                    install -D -m 0644 "$DISCONNECTED_TEMPLATE" "$DISCONNECTED_FILE"
                fi

                # Tunnel von TrutzBox Unterwegs: die Adressen pflegt trutz-backend
                # (gleicheUnterwegsFirewall), Bestand nie ueberschreiben.
                UNTERWEGS_WG_FILE="/etc/nftables.d/unterwegs_wg4.nft"
                if [ ! -e "$UNTERWEGS_WG_FILE" ]; then
                    install -D -m 0644 /usr/share/trutz-network/unterwegs_wg4.nft.dist "$UNTERWEGS_WG_FILE"
                fi

                # VPN-Regeln je Konto wurden 26.11.2026 wieder ausgebaut. Die Mengen-
                # datei von 2.1.0~247 bis ~249 bindet niemand mehr ein; weg damit.
                rm -f /etc/nftables.d/vpn_regeln.nft

                # Geräte im Jugendschutz/Elternmodus: die Adressen pflegt trutz-backend
                # (gleicheJugendDns), Bestand nie ueberschreiben.
                JUGEND_DNS_FILE="/etc/nftables.d/jugend_dns4.nft"
                if [ ! -e "$JUGEND_DNS_FILE" ]; then
                    install -D -m 0644 /usr/share/trutz-network/jugend_dns4.nft.dist "$JUGEND_DNS_FILE"
                fi

                # Geräte mit Tor: die Adressen pflegt trutz-backend (dns-tor.service),
                # Bestand nie ueberschreiben.
                TOR_GERAETE_FILE="/etc/nftables.d/tor_geraete4.nft"
                if [ ! -e "$TOR_GERAETE_FILE" ]; then
                    install -D -m 0644 /usr/share/trutz-network/tor_geraete4.nft.dist "$TOR_GERAETE_FILE"
                fi

                NTP_REDIRECT_FILE="/etc/nftables.d/ntp_redirect_macs.nft"
                NTP_REDIRECT_TEMPLATE="/usr/share/trutz-network/ntp_redirect_macs.nft.dist"

                if [ ! -e "$NTP_REDIRECT_FILE" ]; then
                    install -D -m 0644 "$NTP_REDIRECT_TEMPLATE" "$NTP_REDIRECT_FILE"
                fi

                TRANSPARENT_FILE="/etc/nftables.d/transparent_proxy.nft"
                TRANSPARENT_TEMPLATE="/usr/share/trutz-network/transparent_proxy.nft.dist"

                if [ ! -e "$TRANSPARENT_FILE" ]; then
                    install -D -m 0644 "$TRANSPARENT_TEMPLATE" "$TRANSPARENT_FILE"
                fi

                # QUIC/HTTP-3 (UDP 443) block. Ships ENABLED by default (filled
                # template) so the content filter is not bypassable via QUIC out
                # of the box; the backend rewrites this file when the admin
                # toggles the switch. The include in home_frwd needs the file to
                # exist, so always create it if missing.
                # Firewall variables (interfaces, own networks). The main conf
                # includes the file unconditionally. It is NOT a conffile any
                # more: update-box-ips.sh rewrites it on every network event,
                # so dpkg saw it as locally modified and dropped a
                # vars.nft.dpkg-dist next to it on every template change.
                # Seed it only when missing (fresh image, build chroot) and
                # clear the leftovers of the conffile era.
                VARS_FILE="/etc/vars.nft"
                VARS_TEMPLATE="/usr/share/trutz-network/vars.nft.dist"

                if [ ! -e "$VARS_FILE" ]; then
                    install -D -m 0644 "$VARS_TEMPLATE" "$VARS_FILE"
                fi
                rm -f /etc/vars.nft.dpkg-dist /etc/vars.nft.dpkg-old /etc/vars.nft.dpkg-new

                QUIC_FILE="/etc/nftables.d/quic_block.nft"
                QUIC_TEMPLATE="/usr/share/trutz-network/quic_block.nft.dist"

                if [ ! -e "$QUIC_FILE" ]; then
                    install -D -m 0644 "$QUIC_TEMPLATE" "$QUIC_FILE"
                fi

                # DNS bypass protection (DoT/DoH interception + 53-redirect).
                # Ships ENABLED by default (filled templates) so devices
                # cannot slip past the box resolver out of the box; the
                # backend rewrites the toggle files (block/redirect/dnsmasq)
                # when the admin flips the switch. The resolver-set file is
                # NOT a toggle — it must always exist (table-level include),
                # so refresh it on every upgrade to pick up curated-list
                # updates.
                #
                # The toggle files carry the admin's switch state, so we never
                # create them against an "off" decision — but a file that is
                # currently ON must be refreshed too, otherwise curated-list
                # updates (a newly blocked resolver hostname or IP) never reach
                # a running box: the backend's boot reconcile rewrites them from
                # these same templates, but only at the next backend start, and
                # a trutz-network upgrade alone does not restart the backend
                # (and boxes are not rebooted for updates).
                #
                # Careful with the "is it on?" test — it differs per file:
                # the backend blanks the two nft files when off, but writes a
                # comment line into the dnsmasq drop-in, so "non-empty" would
                # read as ON there and silently re-enable the protection.
                install -D -m 0644 /usr/share/trutz-network/dns_bypass_resolvers.nft.dist \
                    /etc/nftables.d/dns_bypass_resolvers.nft

                DNSBYPASS_BLOCK_FILE="/etc/nftables.d/dns_bypass_block.nft"
                if [ ! -e "$DNSBYPASS_BLOCK_FILE" ] || [ -s "$DNSBYPASS_BLOCK_FILE" ]; then
                    install -D -m 0644 /usr/share/trutz-network/dns_bypass_block.nft.dist \
                        "$DNSBYPASS_BLOCK_FILE"
                fi

                DNSBYPASS_REDIRECT_FILE="/etc/nftables.d/dns_bypass_redirect.nft"
                if [ ! -e "$DNSBYPASS_REDIRECT_FILE" ] || [ -s "$DNSBYPASS_REDIRECT_FILE" ]; then
                    install -D -m 0644 /usr/share/trutz-network/dns_bypass_redirect.nft.dist \
                        "$DNSBYPASS_REDIRECT_FILE"
                fi

                DNSBYPASS_DNSMASQ_FILE="/etc/NetworkManager/dnsmasq.d/60-trutz-dns-bypass.conf"
                DNSBYPASS_DNSMASQ_TEMPLATE="/usr/share/trutz-network/dns-bypass/dnsmasq-dns-bypass.conf.dist"
                # ON is "has at least one address=/ line" — the off-state file
                # holds only a comment.
                if [ ! -e "$DNSBYPASS_DNSMASQ_FILE" ] \
                   || grep -q '^address=/' "$DNSBYPASS_DNSMASQ_FILE"; then
                    if ! cmp -s "$DNSBYPASS_DNSMASQ_TEMPLATE" "$DNSBYPASS_DNSMASQ_FILE"; then
                        install -D -m 0644 "$DNSBYPASS_DNSMASQ_TEMPLATE" \
                            "$DNSBYPASS_DNSMASQ_FILE"
                        # Make the NXDOMAIN entries live now (nft part is
                        # covered by the `nft -f` below, NM reload further down
                        # would also catch this — belt and braces, tolerate
                        # failure).
                        nmcli general reload dns-full 2>/dev/null || true
                    fi
                fi

                # Kurze Namen (ohne Punkt) beim Router aufloesen lassen.
                # Ohne die erzeugte Route landen sie in der Sammelroute des
                # verschluesselten DNS beim Resolver im Internet, der Namen
                # ohne Domaene nicht kennen kann -- gemessen 27.08.2026:
                # "drucker.fritz.box" ging, "drucker" nicht. Das Skript
                # bestimmt die Router-Adresse selbst und schreibt nichts, wenn
                # am Uplink kein privater Namensdienst steht.
                if [ -x /usr/share/trutz-network/ext-unqualified.sh ]; then
                    /usr/share/trutz-network/ext-unqualified.sh || true
                fi

                # NetworkManager-dnsmasq liest *alle* Dateien in
                # /etc/NetworkManager/dnsmasq-shared.d/ und dnsmasq.d/ ein --
                # also auch .dpkg-dist-Reste, die dpkg bei Konffile-Konflikten
                # neben der eigentlichen Datei liegen laesst. Genau das hat
                # uns die br0.conf-Kaskade beschert ("illegal repeated
                # keyword" -> dnsmasq tot -> DHCP weg). Praeventiv abraeumen,
                # bevor wir nftables/Services neu starten.
                for DNSMASQ_DIR in /etc/NetworkManager/dnsmasq-shared.d \
                                   /etc/NetworkManager/dnsmasq.d; do
                    if [ -d "$DNSMASQ_DIR" ]; then
                        find "$DNSMASQ_DIR" -maxdepth 1 -name '*.dpkg-dist' \
                            -delete 2>/dev/null || true
                    fi
                done

                # dnsmasq neu einlesen lassen. NetworkManager startet den
                # DNS-Teildienst nicht von selbst neu, wenn wir eine Datei in
                # dnsmasq.d aendern — ohne diese Zeile wuerde etwa der
                # SRV-Eintrag fuer TrutzChat erst nach dem naechsten Neustart
                # wirken, und TrutzBox-Updates starten die Box NIE neu.
                # Kurzer Aussetzer bei der Namensauflösung, sonst folgenlos.
                # Ordner fuer hostsdir= (VPN-Namen) vorher anlegen; dnsmasq
                # laeuft ohne Rechte und muss ihn lesen koennen.
                install -d -m 755 /var/lib/trutz-network/hosts.d
                # Dasselbe fuer die dnsmasq an br0 (eigener Name nach innen,
                # siehe dnsmasq-shared.d/br0.conf). Sie startet weiter unten
                # mit der Bridge neu, der Ordner muss dann schon da sein.
                install -d -m 755 /var/lib/trutz-network/hosts-innen.d
                nmcli general reload dns-full 2>/dev/null || true

                # Was dieses Paket einschaltet, wird HIER eingeschaltet, gesammelt
                # und mit --no-reload (Ausnahmen mit eigener Begruendung: fail2ban
                # und unbound weiter unten). Ohne den Schalter liest systemd nach
                # jedem einzelnen enable oder mask alle Unit-Dateien neu ein, und
                # so lange haengt jede Abfrage an systemd: gemessen am 11.10.2026
                # 21 Mal in einem Lauf dieses Skripts, zusammen 69 s. Das eine
                # daemon-reload gleich darunter gilt fuer alle zusammen, gestartet
                # wird weiter unten an den alten Stellen. Eine neue Unit gehoert
                # in diese Liste: ein enable weiter unten kostet ohne --no-reload
                # wieder ein eigenes Neueinlesen, und mit --no-reload erfaehrt
                # systemd bis zum naechsten Neueinlesen nichts davon.
                #
                # This will ensure br0 is created and configured on first boot on real hardware
                # make sure /var/lib/firstboot.done does not exist in the image
                systemctl enable --no-reload firstboot.service
                systemctl enable --no-reload trutz-ensure-wan-vlan.service 2>/dev/null || true
                systemctl enable --no-reload trutz-ensure-bridge.service 2>/dev/null || true
                # trutz-normalize-hostname.service is gone (replaced by the
                # name check below, conffile removed via maintscript); its
                # enable link would dangle.
                rm -f /etc/systemd/system/multi-user.target.wants/trutz-normalize-hostname.service
                systemctl enable --no-reload trutz-router-name.timer 2>/dev/null || true
                # Fixed MAC for ports without one of their own (NanoPi R5C), see
                # stable-mac.sh. Replaces the image script of V70 (same unit
                # name, the package file now takes its place). Its .link files
                # used OriginalName= with the renamed port name and never
                # matched; they existed only on test VMs.
                # The image (V70 to V101) ships its own copy of the unit in
                # /etc. dpkg sees it as changed by the admin and keeps it,
                # the package version only lands next to it as .dpkg-dist.
                # The old copy runs the script removed below, so after the
                # next reboot the unit fails and the box reports a failed
                # service (seen 23.11.2026 in the V101.arm test). Put the
                # package version in place whenever the old one is still
                # there; a later upgrade then finds the conffile unchanged.
                SMU=/etc/systemd/system/trutz-stable-mac.service
                if grep -q '^ExecStart=/usr/local/sbin/trutz-stable-mac.sh' "$SMU" 2>/dev/null; then
                    if [ -f "$SMU.dpkg-dist" ]; then
                        mv -f "$SMU.dpkg-dist" "$SMU"
                    else
                        sed -i 's|^ExecStart=/usr/local/sbin/trutz-stable-mac.sh.*|ExecStart=/usr/share/trutz-network/stable-mac.sh boot|' "$SMU"
                    fi
                    systemctl reset-failed trutz-stable-mac.service 2>/dev/null || true
                fi
                rm -f /usr/local/sbin/trutz-stable-mac.sh /etc/systemd/network/70-trutz-port*.link
                chmod 755 /usr/share/trutz-network/stable-mac.sh 2>/dev/null || true
                systemctl enable --no-reload trutz-stable-mac.service 2>/dev/null || true
                # A running box keeps the MAC it has now (router entry, address,
                # port forwards stay). The eMMC address follows with the next
                # reset or tanking. Not in an image chroot: there the build
                # machine's ports would be written down.
                if [ -d /run/systemd/system ] && ! systemd-detect-virt --chroot >/dev/null 2>&1; then
                    /usr/share/trutz-network/stable-mac.sh keep-current >/dev/null 2>&1 || true
                fi
                systemctl enable --no-reload nftables.service
                systemctl enable --no-reload trutz-dienst-ports.timer 2>/dev/null || true
                systemctl enable --no-reload trutz-wlan-scheduler.timer
                systemctl enable --no-reload trutz-network-regulatory.service 2>/dev/null || true
                systemctl mask --no-reload unbound-resolvconf.service 2>/dev/null || true
                systemctl enable --no-reload trutz-encrypted-dns-ensure.service 2>/dev/null || true
                systemctl enable --no-reload trutz-encrypted-dns-default.timer 2>/dev/null || true
                systemctl enable --no-reload trutz-encrypted-dns-watch.timer 2>/dev/null || true
                systemctl enable --no-reload trutzbox-time-early.service 2>/dev/null || true
                systemctl enable --no-reload trutzbox-time-bootstrap.service 2>/dev/null || true
                # fake-hwclock (nur ARM) abschalten: es
                # stellte die Uhr beim Start IMMER auf den gespeicherten Wert, auch
                # rueckwaerts (Debian 0.14 ohne "force"), und nach einem Reset auf den
                # Stand des Images. trutzbox-time-early.service macht dasselbe nur
                # vorwaerts und genauer (Stempel alle 10 min und beim Herunterfahren).
                # Maskiert, nicht entfernt: das Paket bleibt, kein Paketkonflikt.
                # Erst den laufenden Zeitgeber anhalten: maskiert verschwindet sein
                # Dienst beim daemon-reload, dann meldet systemd den Zeitgeber als
                # "failed" (Result: resources), und das stuende als Fehler in der
                # Liste der Dienste (gemessen in der Pruef-VM 16.10.2026).
                if [ -e /usr/lib/systemd/system/fake-hwclock-load.service ] || [ -e /lib/systemd/system/fake-hwclock-load.service ]; then
                    systemctl stop fake-hwclock-save.timer 2>/dev/null || true
                    systemctl mask --no-reload fake-hwclock-load.service fake-hwclock-save.service fake-hwclock-save.timer 2>/dev/null || true
                fi
                systemctl enable --no-reload trutzbox-clock-stamp.timer 2>/dev/null || true
                systemctl enable --no-reload trutzbox-time-sync-watch.timer 2>/dev/null || true

                # ⚠️ Das MUSS vor dem ersten Neuladen der Firewall stehen. Das Paket
                # bringt Drop-ins fuer nftables, openvpn@, wg-quick@, prosody und
                # jitsi-videobridge2 mit; kennt systemd sie noch nicht, laeuft das
                # ExecReload nicht mit, die Kette dienst_ports bleibt leer und der
                # Fernzugriff waere zu. Ausserdem warnt systemd bei jedem Aufruf
                # sichtbar im Update-Protokoll ("changed on disk"), was Anwender
                # zu Recht beunruhigt (gemeldet 18.09.2026).
                # Das ist das einzige Neueinlesen in diesem Skript. Scheitert es,
                # folgt sofort ein zweiter Versuch, dessen Fehlermeldung im
                # Update-Protokoll stehen bleibt. Bisher fing das zweite, strenge
                # daemon-reload hinter dem Laden der Firewall diesen Fall ab.
                if [ -d /run/systemd/system ]; then
                    systemctl daemon-reload 2>/dev/null || systemctl daemon-reload || true
                fi

                echo "reloading firewall rules..."
                if [ ! -d /run/systemd/system ]; then
                    # Bau-/chroot-Umgebung (Image-Bau, debootstrap): kein
                    # laufendes System, dessen Regeln man neu laden könnte —
                    # der nft-Aufruf scheitert dort am fehlenden Netlink-Kanal
                    # (qemu-user: "Unable to initialize Netlink socket",
                    # Befund V73.amd-Bau 26.08.2026) und riss als postinst-
                    # Fehler trutz-setup und trutz-os-config mit. Die Regeln
                    # stehen in Dateien; nftables.service lädt sie beim ersten
                    # Start der Box.
                    echo "chroot/build environment - skipping live firewall reload"
                elif [ -f /etc/nftables.conf ]; then
                    echo "nftables.conf exists"
                    /usr/share/trutz-network/update-box-ips.sh
                    # Safety net for the LOC_IFS migration: update-box-ips.sh
                    # deliberately leaves vars.nft untouched when the box has no
                    # uplink at that moment. The new ruleset references LOC_IFS,
                    # so an old file without it would make the WHOLE ruleset fail
                    # to load, which means no firewall at all. br0 alone is the
                    # safe minimum: every internal port is a bridge member.
                    if [ -f /etc/vars.nft ] && ! grep -q 'define LOC_IFS' /etc/vars.nft; then
                        echo 'define LOC_IFS = { "br0" }' >> /etc/vars.nft
                        echo "vars.nft had no LOC_IFS yet, added a minimal one"
                    fi
                    nft -f /etc/nftables.conf
                    # No `nft list ruleset` here: with the blocklists loaded it
                    # printed thousands of lines into every update log. A load
                    # error still stops the script via set -e.
                    echo "firewall rules loaded"
                else
                    echo "Error: /etc/nftables.conf is missing!" >&2
                fi
                # Idempotent bridge enslaving at every boot + on hotplug. NOT
                # gated by firstboot.done, so a wrong port assignment (renamed
                # NIC, mis-plugged WAN) self-heals instead of staying broken
                # ("link up, no IP"). Run once now so the fix lands without a
                # reboot on existing boxes; tolerate failure on non-NM systems.
                # Provider VLAN on the uplink, if one is configured. Must run
                # BEFORE the bridge step: the bridge must see the finished
                # picture, or it treats the untagged parent of the VLAN as a
                # free LAN port and swallows the uplink. Does nothing at all
                # when /etc/trutz-network/wan-vlan is missing or empty, which
                # is the normal case.
                chmod 755 /usr/share/trutz-network/ensure-wan-vlan.sh 2>/dev/null || true
                chmod 755 /etc/NetworkManager/dispatcher.d/49-trutz-wan-vlan 2>/dev/null || true
                /usr/share/trutz-network/ensure-wan-vlan.sh >/dev/null 2>&1 || true
                chmod 755 /usr/share/trutz-network/ensure-bridge.sh 2>/dev/null || true
                chmod 755 /etc/NetworkManager/dispatcher.d/51-trutz-ensure-bridge 2>/dev/null || true
                chmod 755 /etc/NetworkManager/dispatcher.d/54-trutz-encrypted-dns 2>/dev/null || true
                chmod 755 /etc/NetworkManager/dispatcher.d/56-trutz-zeit 2>/dev/null || true
                systemctl start trutz-ensure-bridge.service 2>/dev/null || true
                # Stable IPv6 interface id on the uplink. The global default in
                # conf.d/10-trutz-ipv6-eui64.conf is ignored by NetworkManager
                # 1.52, and the WAN profile is auto-generated (volatile under
                # /run on a fresh box), so the value has to be re-asserted: at
                # every uplink event via the dispatcher hook, and once right
                # here so existing boxes switch without waiting for a reboot.
                # Costs nothing when the profile is already on eui64.
                chmod 755 /usr/share/trutz-network/ensure-ipv6-eui64.sh 2>/dev/null || true
                chmod 755 /etc/NetworkManager/dispatcher.d/55-trutz-ipv6-eui64 2>/dev/null || true
                /usr/share/trutz-network/ensure-ipv6-eui64.sh >/dev/null 2>&1 || true
                # Check once now that the router resolves the network name to
                # this TrutzBox and register again if not (router-name.sh; at
                # every later start the timer does it). Before the setup is done
                # it also sets the name "trutzbox", as normalize-hostname.sh did.
                # Start --no-block: this postinst runs INSIDE the first-boot
                # auto-update, and the service is ordered After that update, so
                # systemd defers it until the update finishes. The 3 to 6 s
                # re-registration then cannot interrupt a running download.
                chmod 755 /usr/share/trutz-network/router-name.sh 2>/dev/null || true
                systemctl start --no-block trutz-router-name.service 2>/dev/null || true
                # ⚠️ ZUERST daemon-reload: Das Paket bringt Drop-ins fuer nftables,
                # openvpn@, wg-quick@, prosody und jitsi-videobridge2 mit. Ohne
                # das Neueinlesen kennt systemd sie noch nicht, das ExecStartPost
                # laeuft nicht, und die Kette dienst_ports bleibt leer — der
                # Fernzugriff waere zu, obwohl der Server laeuft (gemessen
                # 18.09.2026 auf beiden Boxen).
                # Dieses Neueinlesen ist oben schon geschehen, vor dem ersten
                # Neuladen der Firewall, und seither hat sich an den Units nichts
                # geaendert. Ein zweites Mal ist nicht noetig.
                systemctl restart nftables.service
                echo "nftables.service: $(systemctl is-active nftables.service 2>/dev/null || true)"

                # Anschluesse der abschaltbaren Dienste stehen nicht mehr fest
                # offen, sondern nur solange ihr Dienst laeuft (VPN, Konferenz,
                # Chat). Die Kette wird beim Laden der Firewall, bei jedem Start
                # und Stopp der Dienste und alle fuenf Minuten nachgezogen.
                systemctl start trutz-dienst-ports.timer 2>/dev/null || true
                /usr/share/trutz-network/dienst-ports.sh || true
                echo "Dienst-Anschluesse gesetzt: $(nft list chain inet fw dienst_ports 2>/dev/null | grep -c dport || echo 0)"
                # WLAN time-scheduler — only the timer is enabled; the
                # service file itself is one-shot and triggered by the timer.
                systemctl start trutz-wlan-scheduler.timer || true

                # Regulatory-Domain beim Boot anwenden. Die Unit lag seit jeher
                # im Paket, wurde aber NIE enabled — nach einem Reboot stand die
                # Box auf der Kernel-Vorgabe (00/Chip-Hint) statt auf dem vom
                # Betreiber gewaehlten Standort; erst ein erneuter Standort-
                # Wechsel in der UI setzte ihn wieder. Der Standort bestimmt die
                # erlaubten Kanaele und MUSS jeden Boot ueberleben. (Ordnung: nur After=NetworkManager,
                # keine Before=-Kanten -> kein Zyklus-Risiko.)
                chmod 755 /usr/share/trutz-network/apply-regulatory.sh 2>/dev/null || true

                # WLAN backend switcher (hostapd phase 3). Deliberately NOT
                # enabled/switched here: every box keeps its current backend
                # (fleet default: NetworkManager) until wlan-backend.sh
                # to-hostapd is called explicitly. Only the exec bit is set.
                chmod 755 /usr/share/trutz-network/wlan-backend.sh 2>/dev/null || true
                service rsyslog restart
                deb-systemd-invoke restart procps.service

                # fail2ban: unsere jail.local + nginx-scanner-Filter aktiv
                # schalten. ignoreip schuetzt LAN/VPN, daher keine Gefahr,
                # interne Geraete zu sperren. reload-or-restart ist idempotent
                # und tut nichts Schlimmes, falls fail2ban gerade nicht laeuft.
                if systemctl list-unit-files 2>/dev/null | grep -q '^fail2ban\.service'; then
                    # ignorecommand-Helfer ausfuehrbar machen (die jail.local
                    # ruft ihn pro Treffer auf, damit die Box NIE ihre eigene
                    # oeffentliche/DynDNS-IP bannt -> sonst sperrt sich die Box
                    # via NAT-Hairpin selbst aus, z.B. TrutzRTC). Idempotent.
                    chmod 755 /etc/fail2ban/trutzbox-ignore-ownip.sh 2>/dev/null || true
                    # /64-Rechner fuer IPv6-Sperren, von Aktion und Helfer aufgerufen.
                    chmod 755 /usr/share/trutz-network/ipv6-net64.sh 2>/dev/null || true
                    # Logdateien der aktiven Jails garantieren, BEVOR fail2ban
                    # startet. Sonst bricht fail2ban ab, wenn ein optionaler
                    # Dienst (z.B. TrutzRTC) aus ist und sein nginx-Log nie
                    # angelegt wurde. Das Drop-In trutz-ensure-logs.conf macht
                    # das ausserdem bei jedem Start; hier einmal direkt, damit
                    # ein reload (statt restart) den Effekt nicht verpasst.
                    /usr/share/trutz-network/ensure-fail2ban-logs.sh || true
                    # Nur einschalten, wenn noch nicht geschehen. fail2ban hat auch
                    # ein init.d-Skript; deshalb liest systemd bei jedem enable
                    # dreimal neu ein (zweimal ueber update-rc.d, einmal selbst),
                    # auch wenn sich nichts aendert, und --no-reload spart davon
                    # nur das letzte.
                    systemctl is-enabled --quiet fail2ban 2>/dev/null \
                        || systemctl enable fail2ban 2>/dev/null || true
                    systemctl reload-or-restart fail2ban 2>/dev/null || true
                    # UI-gewaehlte Angriffsschutz-Einstellungen (Sperr-Versuche,
                    # Zeitfenster, Zusatz-Ausnahmen) auf jail.local oben drauf
                    # anwenden, falls der Admin welche gespeichert hat. Ohne
                    # Settings-Datei ein No-Op; ueberlebt so Paket-Updates.
                    chmod 755 /usr/share/trutz-network/apply-fail2ban-settings.sh 2>/dev/null || true
                    /usr/share/trutz-network/apply-fail2ban-settings.sh || true
                fi
                # Encrypted DNS (DoT) — stage-1 plumbing. The feature is
                # OFF by default; it is switched ONLY by encrypted-dns.sh.
                #  * unbound-resolvconf.service would register unbound in
                #    /etc/resolv.conf (fights our seeded "nameserver
                #    127.0.0.1") -> mask it for good.
                #  * unbound.service must not run while the feature is
                #    off. Our conf.d snippet pins :5335, so even a stray
                #    start can never steal :53 from the NM dnsmasq.
                #    The dnsmasq drop-in doubles as the ON-marker: keep
                #    unbound enabled across upgrades only if it exists.
                chmod 755 /usr/share/trutz-network/encrypted-dns.sh 2>/dev/null || true
                if [ ! -e /etc/NetworkManager/dnsmasq.d/50-trutz-encrypted-dns.conf ]; then
                    # Ausschalten nur, wenn er eingeschaltet ist: auch unbound hat
                    # ein init.d-Skript, siehe fail2ban oben. Angehalten wird er
                    # in jedem Fall.
                    if systemctl is-enabled --quiet unbound.service 2>/dev/null; then
                        systemctl disable --now unbound.service 2>/dev/null || true
                    else
                        systemctl stop unbound.service 2>/dev/null || true
                    fi
                fi
                # Boot guard: self-heals the 03.07. failure class (NM dns
                # plugin not spawned at cold boot while the feature is ON).
                # No-op when the feature is off — safe to enable always.
                chmod 755 /usr/share/trutz-network/ensure-encrypted-dns.sh 2>/dev/null || true
                systemctl start trutz-encrypted-dns-ensure.service 2>/dev/null || true

                # Encrypted DNS is the DEFAULT since 30.07.2026. The timer
                # applies it on boxes that were never switched either way and
                # retries every 4 h, so a box behind a line that blocks DoT
                # picks it up as soon as that changes. It does nothing when
                # the feature is already on or the admin switched it off
                # (marker /etc/trutz-network/encrypted-dns.user-off).
                systemctl start trutz-encrypted-dns-default.timer 2>/dev/null || true
                # Once a minute: fall back to plaintext when DoT stops
                # answering. Needed since 10.09.2026: the router's resolvers
                # are kept out of dnsmasq now (they took most queries in
                # plaintext), so nothing masks a dead DoT path any more.
                # No-op while the feature is off.
                systemctl start trutz-encrypted-dns-watch.timer 2>/dev/null || true
                # Apply it right away instead of waiting up to 4 h, but
                # WITHOUT blocking the package installation: the switch
                # proves the DoT path first and takes tens of seconds.
                #
                # On a box that is ALREADY on, the same run now also repairs
                # the runtime forward zone (encrypted-dns.sh auto -> repair).
                # That is what heals a box hit by the resolvconf hook, which
                # wiped the zone on every NM DNS update and left the box
                # recursing in cleartext while every file said "encrypted"
                # (measured 02.09./04.09.2026 on trutzbox-arm). The hook is
                # switched off for good by /etc/default/unbound, shipped by
                # this package since then; no extra call needed here.
                # Same path since 10.09.2026: repair puts the seal in place
                # that keeps the router's resolvers out of dnsmasq, which
                # closes the plaintext leak on boxes that are already on.
                systemctl start --no-block trutz-encrypted-dns-default.service 2>/dev/null || true

                # Time bootstrap: heal a provably wrong clock BEFORE ntpsec
                # starts. NTS cannot sync a clock that is far off (TLS cert
                # validation fails), which froze customer boxes on apt, cert
                # activation and login. The timer keeps an offline floor
                # ("box was already running at this time"), the service does
                # at most ONE plain NTP query and only when the clock is
                # older than the package build date. Not started here: on a
                # running box the clock is either fine or ntpsec's problem;
                # the service is strictly a boot-path guard.
                chmod 755 /usr/share/trutz-network/time-bootstrap.sh 2>/dev/null || true
                mkdir -p /var/lib/trutz
                systemctl start trutzbox-clock-stamp.timer 2>/dev/null || true
                # Uhr ohne Batterie (Konzept v1.3): die Untergrenze laeuft sonst nur
                # beim Start. Hier einmal starten, damit ihr ExecStop schon beim
                # naechsten Herunterfahren den Stempel setzt; auf einer laufenden
                # TrutzBox schreibt sie nur ihre Herkunftszeile.
                systemctl start trutzbox-time-early.service 2>/dev/null || true
                systemctl reset-failed fake-hwclock-save.timer 2>/dev/null || true
                # Alte Einstellung aus dem DHCP des Routers wegraeumen; ntpsec liest
                # sie ab jetzt nicht mehr (IGNORE_DHCP="yes" in /etc/default/ntpsec).
                rm -f /run/ntpsec/ntp.conf.dhcp 2>/dev/null || true

                # Watchdog for the OTHER half of the clock problem: the boot
                # bootstrap only fires when the clock is PROVABLY older than
                # this package. A clock that is merely wrong in a plausible
                # way slips past it and then deadlocks ntpsec forever (NTS
                # needs TLS, TLS needs the clock). The timer checks the
                # kernel sync flag 8 min after boot and hourly afterwards and
                # steps the clock once via plain NTP if it is really off.
                # Started here as well: on a running box the check is free
                # and an already-deadlocked box heals without a reboot.
                systemctl start trutzbox-time-sync-watch.timer 2>/dev/null || true

                # Frueher stand hier ein sed auf /etc/sysctl.conf, das
                # net.ipv4.ip_forward=1 einkommentierte. Die Zeile ist raus:
                # /etc/sysctl.conf existiert ab Debian 13 (trixie) nicht mehr
                # und wird von keinem Paket geliefert — der sed brach dort mit
                # Exit 2 ab und liess das Paket halb konfiguriert zurueck
                # (gemessen 01.09.2026 beim Upgrade-Test einer V65-Box; in der
                # Folge blieben auch trutz-setup und trutz-os-config
                # unkonfiguriert). Wirkungslos war sie ohnehin: denselben Wert
                # setzt etc/sysctl.d/01-trutz-network.conf, und das
                # `sysctl --system` weiter unten liest ihn ein.
                # nf_conntrack muss geladen sein, sonst existieren die
                # net.netfilter.*-Schluessel nicht (Erstinstallation ohne
                # aktive Firewall). Beim Boot uebernimmt das
                # etc/modules-load.d/trutz-network.conf.
                modprobe nf_conntrack 2>/dev/null || true
                modprobe br_netfilter 2>/dev/null || true
                # --system applies /etc/sysctl.conf AND /etc/sysctl.d/*.conf so the
                # conntrack UDP timeouts in 01-trutz-network.conf take effect now,
                # not only after a reboot. (was: sysctl -p, which loads sysctl.conf only)
                # The list of applied files and values goes to /dev/null, errors
                # (stderr) stay visible.
                # Not fatal: during the bookworm -> trixie release upgrade procps
                # is already trixie (no /etc/sysctl.conf) while systemd is still
                # bookworm and ships /etc/sysctl.d/99-sysctl.conf -> ../sysctl.conf,
                # a dangling link. sysctl then applies every other file but exits
                # non-zero, and under set -e this postinst failed and left
                # trutz-network, trutz-setup and trutz-os-config unconfigured
                # (image build V100.amd, 17.11.2026). The values are applied at
                # the next boot by systemd-sysctl in any case.
                sysctl --system >/dev/null \
                    || echo "trutz-network: WARNING: sysctl --system reported errors (see above), values take effect at the next boot" >&2

                # Migration fuer Boxen, die das ntpsec-Cutover (~115) noch mit
                # der falschen Source-Layout-Variante bekommen haben: damals
                # lag /etc/ntpsec/ntp.conf direkt als echte Datei im Paket
                # (statt als displace-Variante mit .trutz-network-Suffix).
                # config-package-devs Postinst-Hook erwartet aber, dass am
                # Original-Pfad ein Symlink steht. Hier sauber migrieren:
                #   * echte Datei loeschen, falls noch vorhanden
                #   * Symlink auf .trutz-network setzen
                # Idempotent — laeuft bei spaeteren Upgrades als No-Op durch.
                NTP_LINK_TARGET=/etc/ntpsec/ntp.conf.trutz-network
                NTP_LINK=/etc/ntpsec/ntp.conf
                if [ -e "$NTP_LINK_TARGET" ]; then
                    if [ -L "$NTP_LINK" ]; then
                        # bereits Symlink — pruefen ob er aufs richtige Ziel
                        # zeigt; sonst neu setzen.
                        CURRENT_TARGET=$(readlink "$NTP_LINK")
                        if [ "$CURRENT_TARGET" != "ntp.conf.trutz-network" ] && \
                           [ "$CURRENT_TARGET" != "$NTP_LINK_TARGET" ]; then
                            ln -sf ntp.conf.trutz-network "$NTP_LINK"
                        fi
                    else
                        # echte Datei oder gar nichts — durch Symlink ersetzen.
                        rm -f "$NTP_LINK"
                        ln -s ntp.conf.trutz-network "$NTP_LINK"
                    fi
                fi

                # AppArmor-Override: das Stock-Profil /etc/apparmor.d/usr.sbin.ntpd
                # erlaubt ntpd nur /etc/ntpsec/ntp.conf bzw. /etc/hosts. AppArmor
                # prueft den resolvten Ziel-Pfad, nicht den Symlink — und unser
                # displace verdraengt GLEICH ZWEI Dateien, die ntpd liest:
                #   * /etc/ntpsec/ntp.conf -> ntp.conf.trutz-network  (NTS-Konfig)
                #   * /etc/hosts           -> hosts.trutz-network     (Name-Resolve
                #     der NTS-Hostnamen ptbtime*.ptb.de / nts.netnod.se)
                # Dazu kommt das Drop-in mit den vom Admin eingetragenen Zeitservern:
                #   * /etc/ntpsec/ntp.conf.d/custom.conf  (per includefile aus ntp.conf)
                # Das ist KEIN displace-Pfad, sondern schlicht ein Verzeichnis, das im
                # Stock-Profil nicht vorkommt. Ohne Regel liest ntpd das include NICHT
                # und ignoriert die eingetragenen Server STILL -- die Datei ist korrekt
                # geschrieben, `ntpq -p` zeigt sie aber nie. Auf TB64 genau so passiert.
                # Fehlt der Read auf den Ziel-Pfad, blockt AppArmor ("DENIED,
                # operation=open"): bei ntp.conf startet ntpd ohne Peers, bei
                # /etc/hosts spammt ntpd beim Boot im Sekundentakt das Audit-Log
                # (funktional unkritisch, faellt auf dns zurueck). Den Site-
                # Override-Include /etc/apparmor.d/local/usr.sbin.ntpd (vom
                # ntpsec-Paket mitgeliefert) PRO REGEL idempotent erweitern —
                # so bekommen auch Bestandsinstallationen mit aelterem (Marker-
                # basiertem) Block die fehlende Zeile nachgereicht; fremde lokale
                # Anpassungen bleiben unangetastet.
                AA_LOCAL=/etc/apparmor.d/local/usr.sbin.ntpd
                AA_HEADER='# trutz-network: allow ntpd to read displace-suffix variants'
                if [ -f "$AA_LOCAL" ]; then
                    aa_changed=0
                    grep -qF "$AA_HEADER" "$AA_LOCAL" || {
                        printf '\n%s\n' "$AA_HEADER" >> "$AA_LOCAL"
                        aa_changed=1
                    }
                    for aa_rule in \
                        "/etc/ntpsec/ntp.conf.trutz-network r," \
                        "/etc/ntpsec/ntp.conf.trutz-network-orig r," \
                        "/etc/ntpsec/ntp.conf.d/ r," \
                        "/etc/ntpsec/ntp.conf.d/custom.conf r," \
                        "/etc/ntpsec/ntp.conf.d/builtin.conf r," \
                        "/etc/ntpsec/ntp.conf.d/fallback.conf r," \
                        "/etc/hosts.trutz-network r,"; do
                        grep -qF "$aa_rule" "$AA_LOCAL" || {
                            echo "$aa_rule" >> "$AA_LOCAL"
                            aa_changed=1
                        }
                    done
                    if [ "$aa_changed" = 1 ] && [ -e /etc/apparmor.d/usr.sbin.ntpd ] \
                       && command -v apparmor_parser >/dev/null 2>&1; then
                        apparmor_parser -r /etc/apparmor.d/usr.sbin.ntpd 2>/dev/null || true
                    fi
                fi

                # NTPsec mit der per displace eingesetzten privacy-hardened
                # Konfiguration (PTB + Netnod, NTS-authentifiziert) neu laden.
                # try-restart laesst ntpsec in Ruhe, wenn der Service gerade
                # nicht laeuft — also keine harten Fehler durchs Paket-Install.
                systemctl try-restart ntpsec.service 2>/dev/null || true

                # Tor fuer Geraete: Namensdienst und TransPort in /etc/tor/torrc
                # (Konzept DNS-Tor v1.8). Fehler duerfen das Paket nicht abbrechen.
                /usr/share/trutz-network/tor-geraete.sh || true
                ;;
            *)
                echo -n "$DEBIAN_VERSION unknown version"
        esac

        # Sicherstellen, dass der EEE/WOL-Hook von ifupdown ausgefuehrt
        # wird (if-up.d-Scripts muessen das execute-Bit haben).
        if [ -f /etc/network/if-up.d/trutzbox-ethtool ]; then
            chmod 755 /etc/network/if-up.d/trutzbox-ethtool
        fi

        # Empfangsring der igb-Ports (siehe etc/systemd/network/50-trutz-igb-
        # rxring.link): die .link-Datei greift erst beim naechsten Boot. Damit
        # der Kunde nicht bis dahin warten muss, hier einmalig direkt setzen.
        # ethtool -G setzt den Port kurz zurueck (Link 1-2 s weg), darum nur,
        # wenn der Ring wirklich noch kleiner ist. Fehler sind unkritisch.
        if command -v ethtool >/dev/null 2>&1; then
            udevadm control --reload 2>/dev/null || true
            for _dev in /sys/class/net/*/device; do
                [ -e "$_dev" ] || continue
                _if=${_dev%/device}; _if=${_if##*/}
                _drv=$(basename "$(readlink "$_dev/driver" 2>/dev/null)" 2>/dev/null)
                [ "$_drv" = "igb" ] || continue
                _cur=$(ethtool -g "$_if" 2>/dev/null | awk '/^Current/{f=1} f && /^RX:/{print $2; exit}')
                if [ -n "$_cur" ] && [ "$_cur" -lt 2048 ]; then
                    ethtool -G "$_if" rx 2048 2>/dev/null || true
                    logger -i -t trutz-network "rx ring $_if $_cur -> 2048 (igb)"
                fi
            done
        fi

        # IPv4 vor IPv6 in getaddrinfo() bevorzugen. Linux-Default ist
        # umgekehrt (globale v6-Precedence 40 > v4 10), Folge: Box-eigene
        # Verbindungen ueber libc (curl, NTP, Mail-Relay, Node-Apps) wuerden
        # bei Dual-Stack-Zielen v6 nehmen und damit die v4-only nftables-
        # Allow/Block-Listen (insb. blocked_inet4 und die INPUT-Allowlist)
        # umgehen. Die eine precedence-Zeile reicht — keine v6-Erzwingung,
        # nur Reihenfolge bei Dual-Stack. Idempotent: nur appendet, wenn
        # noch nicht vorhanden. /etc/gai.conf gehoert libc-bin, daher KEIN
        # Paket-File-Conflict, sondern Inline-Edit per postinst.
        GAI_MARKER='# trutz-network: prefer IPv4 over IPv6'
        if [ -f /etc/gai.conf ] && ! grep -q "$GAI_MARKER" /etc/gai.conf; then
            {
                echo ""
                echo "$GAI_MARKER"
                echo "precedence ::ffff:0:0/96  100"
            } >> /etc/gai.conf
        fi

        # /etc/resolv.conf-Sanity: einige Box-Konfigurationen haben weder
        # resolvconf installiert noch eine resolv.conf-Datei -- glibc faellt
        # dann auf 127.0.0.1 UND ::1 als implizite Resolver zurueck. ::1
        # antwortet ggf. mit "connection refused" und Tools wie host/dig
        # haengen pro Anfrage ~2 s. Auf dem Loopback dnsmasq-Resolver
        # ausrichten und ueber ein NM-Drop-In auch v6-Loopback binden.
        if [ ! -e /etc/resolv.conf ]; then
            cat > /etc/resolv.conf <<'EOF_RESOLV'
# Managed by trutz-network (postinst): point libc at the local dnsmasq.
# v6-loopback binding is configured in
# /etc/NetworkManager/dnsmasq.d/loopback-v6.conf.
nameserver 127.0.0.1
options edns0 timeout:2 attempts:1
EOF_RESOLV
            chmod 644 /etc/resolv.conf
        fi
        # NetworkManager-dnsmasq neu laden, damit das v6-Loopback-Drop-In
        # wirksam wird -- 'reload' triggert NM, dnsmasq neu zu starten, ohne
        # die Connection-Profile anzufassen (kein Link-Flap, kein Reboot).
        if systemctl is-active --quiet NetworkManager; then
            systemctl reload NetworkManager || true
        fi

        # LAN-Bridge neu starten, wenn ihre dnsmasq veraltete Einstellungen
        # hat. Diese dnsmasq (DHCP und DNS fuer alle Geraete im internen Netz)
        # liest dnsmasq-shared.d und dhcp-pool-hosts nur beim Start, und
        # NetworkManager startet sie nur zusammen mit der Bridge. Ein Update
        # allein aendert an ihr also nichts, und Updates starten die Box nie
        # neu. Anlass 14.09.2026: 24 h Leasezeit und freie Adressen .1 bis .49
        # (siehe /usr/share/trutz-network/dhcp-pool-hosts) haetten sonst bis
        # zum naechsten Neustart der Box gewartet.
        #
        # Neu gestartet wird nur, wenn eine dieser Dateien NACH dem Start der
        # laufenden dnsmasq geschrieben wurde. Massstab ist die ctime: dpkg
        # setzt die mtime auf den Stand beim Paketbau, die ctime auf den
        # Moment der Installation. Ein Update ohne Aenderung an diesen Dateien
        # laesst die Bridge in Ruhe. Kosten: LAN und WLAN wenige Sekunden weg;
        # den WLAN-Anschluss einer hostapd-Box haengt der Dispatcher
        # 53-trutz-hostapd-bridge wieder ein.
        BR0_PIDFILE=/run/nm-dnsmasq-br0.pid
        if [ -d /run/systemd/system ] && [ -s "$BR0_PIDFILE" ] \
           && systemctl is-active --quiet NetworkManager; then
            br0_age=$(ps -o etimes= -p "$(cat "$BR0_PIDFILE")" 2>/dev/null | tr -d ' ' || true)
            br0_changed=""
            if [ -n "$br0_age" ]; then
                br0_started=$(( $(date +%s) - br0_age ))
                for br0_file in /etc/NetworkManager/dnsmasq-shared.d/* \
                                /usr/share/trutz-network/dhcp-pool-hosts; do
                    [ -f "$br0_file" ] || continue
                    if [ "$(stat -c %Z "$br0_file")" -gt "$br0_started" ]; then
                        br0_changed="$br0_changed ${br0_file##*/}"
                    fi
                done
            fi
            br0_con=$(nmcli -g GENERAL.CONNECTION device show br0 2>/dev/null || true)
            if [ -n "$br0_changed" ] && [ -n "$br0_con" ]; then
                logger -t trutz-network "LAN-Bridge wird neu gestartet, neue Einstellungen:$br0_changed"
                br0_old=$(cat "$BR0_PIDFILE" 2>/dev/null || true)
                nmcli --wait 60 connection up "$br0_con" >/dev/null 2>&1 || true
                # nmcli kehrt zurueck, bevor die neue dnsmasq laeuft (in der
                # Test-VM 1 s davor). Fertig ist es erst mit ihrer neuen PID.
                br0_new=""
                for br0_i in $(seq 1 30); do
                    br0_new=$(cat "$BR0_PIDFILE" 2>/dev/null || true)
                    if [ -n "$br0_new" ] && [ "$br0_new" != "$br0_old" ] && kill -0 "$br0_new" 2>/dev/null; then
                        break
                    fi
                    br0_new=""
                    sleep 1
                done
                if [ -n "$br0_new" ]; then
                    logger -t trutz-network "LAN-Bridge laeuft wieder, dnsmasq mit neuen Einstellungen"
                else
                    logger -t trutz-network "LAN-Bridge: nach 30 s keine neue dnsmasq, bitte pruefen"
                fi
            fi
        fi

        # WLAN-Kompatibilitaet: Bestandsboxen haben ihr AP-Profil evtl. noch
        # mit key-mgmt=sae (WPA3-only). Auf den verbauten Karten (ath9k/AR928X,
        # RTL8822CE) sperrt ein SAE-only-AP WPA2-only-Geraete aus (IoT wie
        # Wetterstation/Heizung, aeltere Handys) -- deren korrektes Passwort
        # wird scheinbar "nicht akzeptiert", nur Android/WPA3 kommt rein. Die
        # Paket-Templates sind auf WPA2-PSK gezogen; hier die bereits AKTIVEN
        # AP-Profile nachziehen, damit der Fix ohne UI-Handgriff greift. Nur
        # mode=ap-Profile anfassen; Client-/Uplink-Profile bleiben unberuehrt.
        # Idempotent.
        NM_SYSCONN=/etc/NetworkManager/system-connections
        if [ -d "$NM_SYSCONN" ] && systemctl is-active --quiet NetworkManager; then
            wlan_fixed=0
            while IFS= read -r -d '' cf; do
                grep -q '^mode=ap' "$cf" || continue
                grep -q '^key-mgmt=sae' "$cf" || continue
                sed -i 's/^key-mgmt=sae/key-mgmt=wpa-psk/; s/^pmf=required/pmf=0/' "$cf"
                wlan_fixed=1
            done < <(find "$NM_SYSCONN" -maxdepth 1 -type f -print0 2>/dev/null)
            if [ "$wlan_fixed" = 1 ]; then
                nmcli connection reload 2>/dev/null || true
                # betroffene AP-Connection kurz neu hochfahren, damit WPA2
                # sofort statt erst nach Reboot aktiv ist (kurzer WLAN-Flap;
                # WPA2 kommt auf diesen Karten zuverlaessiger hoch als SAE).
                while IFS= read -r -d '' cf; do
                    grep -q '^mode=ap' "$cf" || continue
                    apid=$(sed -n 's/^id=//p' "$cf" | head -1)
                    [ -n "$apid" ] && nmcli connection up "$apid" 2>/dev/null || true
                done < <(find "$NM_SYSCONN" -maxdepth 1 -type f -print0 2>/dev/null)
            fi
        fi
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
