#!/bin/sh
# sethostname — set the network name of the box everywhere it matters, without
# a reboot (27.08.2026).
#
# The name the customer picks in the setup wizard (or later under "Allgemeine
# Einstellungen") has to work in THREE places, and until now only the first one
# was maintained:
#
#   1. on the box itself      -> /etc/hostname + /etc/hosts (127.0.1.1)
#   2. in the internal net    -> /etc/hosts.dnsmasq, the additional hosts file
#                                both dnsmasq instances read (the NetworkManager
#                                one on 127.0.0.1 and the shared-mode one that
#                                serves br0 = LAN, WLAN and VPN). It carried a
#                                HARDCODED "TrutzBox" line, so a renamed box was
#                                not resolvable from the bridge at all.
#   3. on the customer router -> DHCP option 12, which NetworkManager takes from
#                                the system hostname and only sends in a fresh
#                                DHCP transaction.
#
# (3) is the only part that needs more than a file edit, and it does NOT need a
# reboot: a connection down+up makes NetworkManager send a new DISCOVER with the
# new option 12. A plain reactivate/renew is not enough — verified on a
# FRITZ!Box on 15.07.2026, see normalize-hostname.sh in trutz-network, which
# uses the same mechanism for the first-boot normalization.
#
# Usage:  sethostname <name> [--no-announce]
#         sethostname <name> --announce-only    (internal: background phase)
#
# The call returns as soon as the local part is done (phase 1). The uplink
# re-registration and the certificate reissue (phase 2) continue detached,
# because the ~3-6 s uplink blip would otherwise kill the HTTP response of the
# caller that asked for the rename. Phase 2 never touches br0, so LAN, WLAN and
# VPN clients keep their connection.

set -e

NAME=$(printf '%s' "${1:-}" | tr -d '[:space:]')
MODE=${2:-}
# Absolute path to this script: phase 2 re-executes it detached, and a relative
# $0 would break that as soon as somebody calls the script from another
# directory.
SELF=$(readlink -f "$0" 2>/dev/null || echo "$0")

STATUS_TAG=trutz-sethostname
MARKER=/etc/comidio/hostname-user-set
# Sperre gegen eine zweite Umbenennung, solange Phase 2 laeuft. Ohne sie ging
# ein zweiter Klick in der Oberflaeche waehrend des Uplink-Aussetzers spurlos
# verloren (28.08.2026): die Anfrage erreichte die Box nie, und der Benutzer sah
# nur, dass nichts passierte.
LOCK=/run/trutz-sethostname.lock
LOCK_MAX_AGE=120
WAN_PIN_FILE=/etc/trutz-network/wan-interface
FALLBACK_BRIDGE_IP=192.168.195.200

# Both copies of each file: the active one and the package-managed displace
# copy. Keeping them in sync is what makes the displace warning of trutz-network
# honest — they had drifted apart before, because nothing maintained the name in
# both (see trutz-setup lib/network/hostname.ts, 26.08.2026).
HOSTS_FILES="/etc/hosts /etc/hosts.trutz-network"
DNSMASQ_HOSTS_FILES="/etc/hosts.dnsmasq /etc/hosts.dnsmasq.trutz-network"

log() { logger -t "$STATUS_TAG" "$*" 2>/dev/null || true; echo "sethostname: $*"; }

usage() {
    echo "usage: sethostname <name> [--no-announce]" >&2
    exit 2
}

# Die Sperre gilt, solange der Prozess von Phase 2 lebt — und ersatzweise fuer
# LOCK_MAX_AGE Sekunden ab dem Start, damit ein abgestuerzter Lauf die Box nicht
# dauerhaft blockiert.
lock_held() {
    [ -f "$LOCK" ] || return 1
    pid=$(sed -n 's/^pid=//p' "$LOCK" 2>/dev/null | head -n1)
    if [ -n "$pid" ] && [ "$pid" != "starting" ] && [ -d "/proc/$pid" ]; then
        return 0
    fi
    started=$(sed -n 's/^started=//p' "$LOCK" 2>/dev/null | head -n1)
    now=$(date +%s 2>/dev/null || echo 0)
    if [ -n "$started" ] && [ "$started" -gt 0 ] 2>/dev/null \
       && [ $((now - started)) -lt "$LOCK_MAX_AGE" ]; then
        return 0
    fi
    return 1
}

write_lock() {
    printf 'pid=%s\nstarted=%s\nname=%s\n' "$1" "$(date +%s 2>/dev/null || echo 0)" "$NAME" > "$LOCK" 2>/dev/null || true
}

# RFC-952/1123 label: lowercase letters, digits, hyphens; starts and ends
# alphanumeric; at most 63 characters. Uppercase is rejected rather than folded,
# so what the customer typed is exactly what the box announces.
valid_name() {
    printf '%s' "$1" | grep -qE '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'
}

[ -n "$NAME" ] || usage
valid_name "$NAME" || { echo "sethostname: invalid name '$NAME'" >&2; exit 2; }

# The address the internal name has to point at: br0's own address, with the
# shipped default as fallback for the (short) window before the bridge exists.
bridge_ip() {
    ip -4 -o addr show dev br0 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | head -n1
}

# Canonical path list, so a symlinked /etc/hosts is written once, not twice.
canonical_files() {
    seen=""
    for f in $1; do
        [ -e "$f" ] || continue
        c=$(readlink -f "$f" 2>/dev/null || echo "$f")
        case " $seen " in *" $c "*) continue ;; esac
        seen="$seen $c"
        echo "$c"
    done
}

# Replace (or append) the 127.0.1.1 self-entry.
update_hosts_file() {
    path=$1
    tmp="${path}.sethostname.$$"
    # [[:blank:]], not [ \t]: inside a POSIX bracket expression "\t" is the two
    # characters backslash and t, so the pattern would miss the tab this very
    # function writes — and every call appended one more self-entry.
    if grep -qE '^127\.0\.1\.1[[:blank:]]' "$path" 2>/dev/null; then
        sed "s|^127\.0\.1\.1[[:blank:]].*$|127.0.1.1\t${NAME}|" "$path" > "$tmp"
    else
        { cat "$path"; printf '127.0.1.1\t%s\n' "$NAME"; } > "$tmp"
    fi
    # cat instead of mv: keeps owner, group and mode of the original file.
    cat "$tmp" > "$path"
    rm -f "$tmp"
}

# Rewrite the box's own entry in the dnsmasq hosts file. dnsmasq matches names
# case-insensitively, so the historic "TrutzBox" spelling keeps working.
#
# The aliases trutzbox/TrutzBox stay INTERNAL on purpose: handbook, mail and
# XMPP setup instructions all name them, and inside one home network they point
# at exactly one box. They are deliberately NOT announced outwards (DHCP option
# 12 carries the chosen name alone) — with several TrutzBoxes behind the same
# router a shared external name would collide.
update_dnsmasq_hosts_file() {
    path=$1
    ip=$2
    names="$NAME ${NAME}.sec"
    for alias in trutzbox TrutzBox TrutzBox.sec; do
        # skip an alias the chosen name already covers (case-insensitively)
        low_alias=$(printf '%s' "$alias" | tr 'A-Z' 'a-z')
        low_name=$(printf '%s' "$NAME" | tr 'A-Z' 'a-z')
        [ "$low_alias" = "$low_name" ] && continue
        [ "$low_alias" = "${low_name}.sec" ] && continue
        names="$names $alias"
    done

    tmp="${path}.sethostname.$$"
    # Drop every existing mapping of the bridge address, then write ours. Other
    # entries in the file (if an admin added any) are kept untouched.
    grep -vE "^[[:space:]]*${ip}[[:space:]]" "$path" > "$tmp" 2>/dev/null || true
    printf '%s %s\n' "$ip" "$names" >> "$tmp"
    cat "$tmp" > "$path"
    rm -f "$tmp"
}

# Heal a displace link that an earlier in-place edit (sed -i style) replaced
# with a real file: sed writes a temp file and renames it OVER the link path,
# leaving a regular file with the target's content — exactly what happened on
# the boxes renamed by hand in mid-August 2026, before this script existed.
# Only heals when file and target are byte-identical, so a deliberate admin
# override (config-package-dev allows replacing the link on purpose) is never
# destroyed. mv -T over the file is an atomic rename; ln -sfn would be
# unlink+symlink with a window where the path does not resolve.
heal_displace_link() {
    file=$1; target=$2
    dir=$(dirname "$file")
    [ ! -L "$file" ] && [ -f "$file" ] && [ -f "$dir/$target" ] || return 0
    cmp -s "$file" "$dir/$target" || return 0
    tmp="$file.heal.$$"
    if ln -s "$target" "$tmp" 2>/dev/null && mv -T "$tmp" "$file" 2>/dev/null; then
        log "restored displace link $file -> $target"
    else
        rm -f "$tmp"
    fi
}

# --- WAN interface, same precedence as ensure-bridge.sh/normalize-hostname.sh
wan_from_pin() {
    [ -r "$WAN_PIN_FILE" ] || return 1
    pin=$(grep -vE '^[[:space:]]*#' "$WAN_PIN_FILE" 2>/dev/null | tr -d '[:space:]' | head -n1)
    [ -n "$pin" ] || return 1
    [ -d "/sys/class/net/$pin" ] && { echo "$pin"; return 0; }
    for d in /sys/class/net/*; do
        i=$(basename "$d")
        mac=$(cat "$d/address" 2>/dev/null)
        [ "$(printf '%s' "$mac" | tr 'A-Z' 'a-z')" = "$(printf '%s' "$pin" | tr 'A-Z' 'a-z')" ] \
            && { echo "$i"; return 0; }
    done
    return 1
}

announce_phase() {
    WAN_IF=$(wan_from_pin || true)
    [ -n "$WAN_IF" ] || WAN_IF=$(ip route show default 2>/dev/null | awk '/default/ {print $5; exit}')

    if [ -z "$WAN_IF" ]; then
        log "no WAN interface found — the router will learn '$NAME' on the next DHCP renewal"
    else
        # down+up, not reactivate: only a fresh DISCOVER carries the new option
        # 12. Brief uplink blip (~3-6 s); br0 and with it LAN/WLAN/VPN stay up.
        CONN=$(nmcli -t -g GENERAL.CONNECTION device show "$WAN_IF" 2>/dev/null || true)

        # A static uplink sends no DHCP at all, so there is nothing for the
        # router to re-learn — bouncing it would cost an outage and buy
        # nothing. The box is then reached by address, by its internal name or
        # by whatever the router has statically mapped.
        METHOD=""
        if [ -n "$CONN" ]; then
            METHOD=$(nmcli -t -g ipv4.method connection show "$CONN" 2>/dev/null || true)
        fi
        if [ "$METHOD" = "manual" ]; then
            log "uplink '$WAN_IF' is configured statically — no DHCP re-registration needed"
            WAN_IF=""
        fi
    fi

    if [ -n "$WAN_IF" ]; then
        log "re-registering on WAN '$WAN_IF' (connection '${CONN:-none}') so the router learns '$NAME'"
        if [ -n "$CONN" ]; then
            nmcli connection down "$CONN" >/dev/null 2>&1 || true
            sleep 2
            nmcli connection up "$CONN" >/dev/null 2>&1 \
                || nmcli device connect "$WAN_IF" >/dev/null 2>&1 \
                || nmcli device reapply "$WAN_IF" >/dev/null 2>&1 || true
        else
            nmcli device disconnect "$WAN_IF" >/dev/null 2>&1 || true
            sleep 2
            nmcli device connect "$WAN_IF" >/dev/null 2>&1 \
                || nmcli device reapply "$WAN_IF" >/dev/null 2>&1 || true
        fi

        # Wait for the new lease: the certificate below builds its SAN from
        # `hostname -A` (the FQDN the router hands back, e.g. name.fritz.box),
        # which is empty until the lease is in.
        i=0
        while [ -z "$(hostname -I 2>/dev/null | tr -d ' \n')" ] && [ "$i" -lt 60 ]; do
            i=$((i + 1))
            sleep 1
        done
        sleep 3
    fi

    # New name -> new web certificate. certs.sh reissues on its own as soon as
    # the current hostname or FQDN is missing from the SAN; the unit is just the
    # documented way to run it (it waits for an IP first). Same Root CA, so
    # clients do not have to install anything again.
    # `systemctl list-unit-files` exits 0 even when it matched nothing, so the
    # unit has to be grepped for, not just asked about.
    if systemctl list-unit-files trutz-lib.service 2>/dev/null | grep -q '^trutz-lib\.service'; then
        systemctl restart trutz-lib.service >/dev/null 2>&1 || log "certificate refresh failed"
    elif [ -x /usr/lib/trutz-lib/certificate/certs.sh ]; then
        /usr/bin/bash /usr/lib/trutz-lib/certificate/certs.sh >/dev/null 2>&1 || log "certificate refresh failed"
    fi

    # nginx serves the admin UI under the new name and has to pick the new
    # certificate up. Mail and XMPP keep serving the previous certificate until
    # their next start — it stays valid for the names and addresses those
    # clients were set up with.
    # Only a configuration that passes its test: with a broken one the reload
    # fails anyway and the restart behind it stopped the running nginx for good
    # (seen 13.10.2026). nginx then keeps what it has loaded.
    if systemctl is-active --quiet nginx 2>/dev/null; then
        if nginx -t -q >/dev/null 2>&1; then
            systemctl reload nginx >/dev/null 2>&1 || systemctl restart nginx >/dev/null 2>&1 || true
        else
            log "nginx configuration does not pass its test — nginx keeps running with the previous configuration and certificate"
        fi
    fi

    log "done — box is '$NAME', announced on the uplink and resolvable in the internal network"
}

if [ "$MODE" = "--announce-only" ]; then
    write_lock "$$"
    announce_phase
    rm -f "$LOCK"
    exit 0
fi

# --- phase 1: local, fast, everything the internal network needs ------------
if lock_held; then
    running=$(sed -n 's/^name=//p' "$LOCK" 2>/dev/null | head -n1)
    log "rename to '${running:-?}' still in progress — refusing '$NAME'"
    exit 3
fi
write_lock starting

log "setting network name to '$NAME'"

hostnamectl set-hostname "$NAME"

for f in $(canonical_files "$HOSTS_FILES"); do
    update_hosts_file "$f"
done

BRIDGE_IP=$(bridge_ip)
[ -n "$BRIDGE_IP" ] || BRIDGE_IP=$FALLBACK_BRIDGE_IP
for f in $(canonical_files "$DNSMASQ_HOSTS_FILES"); do
    update_dnsmasq_hosts_file "$f" "$BRIDGE_IP"
done

# After the updates both copies are freshly in sync, so a link broken by an
# earlier in-place edit can be healed right here without losing anything.
heal_displace_link /etc/hosts hosts.trutz-network
heal_displace_link /etc/hosts.dnsmasq hosts.dnsmasq.trutz-network

# SIGHUP makes dnsmasq re-read /etc/hosts and every addn-hosts file and drop its
# cache — no restart, so no DHCP interruption for the clients on the bridge.
# From here on the new name resolves for LAN, WLAN and VPN.
pkill -HUP dnsmasq 2>/dev/null || true

mkdir -p "$(dirname "$MARKER")"
printf '%s\n' "$NAME" > "$MARKER"

log "local part done; '$NAME' resolves in the internal network now"

# --- phase 2: uplink + certificate, detached --------------------------------
if [ "$MODE" != "--no-announce" ]; then
    setsid "$SELF" "$NAME" --announce-only </dev/null >/dev/null 2>&1 &
else
    rm -f "$LOCK"
fi

exit 0
