#!/usr/bin/env bash
# mdns-host-setup.sh — pin the HOST avahi-daemon to the LAN interface so it
# stops self-colliding across docker bridges ("Local name collision"), which
# is what blocks the mDNS (.local) path on a host with many interfaces.
#
# Detects the LAN NIC from HOST_LAN_IP (.env), sets allow-interfaces=<nic> in
# /etc/avahi/avahi-daemon.conf (idempotent, backs up first), restarts avahi.
# Re-execs itself with sudo if not root. Run: tooling/mdns-host-setup.sh
set -euo pipefail
cd "$(dirname "$0")/.."

[ -f .env ] && { set -a; . ./.env; set +a; }
: "${HOST_LAN_IP:?HOST_LAN_IP unset (set in .env)}"

nic="$(ip -o -4 addr show | awk -v ip="$HOST_LAN_IP" 'index($0, " "ip"/"){print $2; exit}')"
[ -n "$nic" ] || { echo "ERROR: no interface found with IP $HOST_LAN_IP" >&2; exit 1; }
echo "LAN interface for ${HOST_LAN_IP}: ${nic}"

conf=/etc/avahi/avahi-daemon.conf
[ -f "$conf" ] || { echo "ERROR: $conf not found — is avahi-daemon installed?" >&2; exit 1; }

# Need root to edit the conf + restart the service.
if [ "$(id -u)" -ne 0 ]; then
  echo "escalating with sudo…"
  exec sudo "$0" "$@"
fi

# Already pinned to this NIC? nothing to do.
if grep -qE "^allow-interfaces=${nic}([,[:space:]]|$)" "$conf"; then
  echo "already set: allow-interfaces=${nic}"
else
  cp -a "$conf" "${conf}.bak.$(date +%s)"
  if grep -qE '^allow-interfaces=' "$conf"; then
    sed -i -E "s/^allow-interfaces=.*/allow-interfaces=${nic}/" "$conf"
  elif grep -qE '^#\s*allow-interfaces=' "$conf"; then
    sed -i -E "s/^#\s*allow-interfaces=.*/allow-interfaces=${nic}/" "$conf"
  else
    # insert right after the [server] section header
    sed -i -E "/^\[server\]/a allow-interfaces=${nic}" "$conf"
  fi
  echo "set allow-interfaces=${nic} (backup: ${conf}.bak.*)"
fi

echo "restarting avahi-daemon…"
systemctl restart avahi-daemon
sleep 1
systemctl is-active --quiet avahi-daemon && echo "avahi-daemon active" || { echo "ERROR: avahi-daemon not active" >&2; exit 1; }
grep -E '^allow-interfaces=' "$conf"
