#!/bin/sh
# Publish A records for the stack's service names on .local via the HOST's
# avahi-daemon (reached over its mounted D-Bus socket). One avahi-publish per
# name; if any drops the container exits so Docker restarts it.
set -eu

: "${BASE_DOMAIN:?BASE_DOMAIN unset}"
: "${HOST_LAN_IP:?HOST_LAN_IP unset}"

case "$BASE_DOMAIN" in
  *.local) ;;
  *) echo "WARN: mDNS resolves only .local — BASE_DOMAIN=$BASE_DOMAIN will NOT be discoverable via avahi. Set BASE_DOMAIN=*.local to use mDNS." >&2 ;;
esac

bus="${DBUS_SYSTEM_BUS_ADDRESS:-unix:path=/run/dbus/system_bus_socket}"
sock=${bus#unix:path=}
if [ ! -S "$sock" ]; then
  echo "ERROR: host D-Bus socket '$sock' not found. Mount the host's" >&2
  echo "       /run/dbus/system_bus_socket and ensure avahi-daemon runs on the host." >&2
  exit 1
fi
export DBUS_SYSTEM_BUS_ADDRESS="$bus"

pids=""
for n in "$BASE_DOMAIN" "auth.$BASE_DOMAIN" "packwiz.$BASE_DOMAIN" "mc.$BASE_DOMAIN"; do
  echo "mDNS publish (host avahi): $n -> $HOST_LAN_IP"
  avahi-publish -a "$n" "$HOST_LAN_IP" &
  pids="$pids $!"
done

# shellcheck disable=SC2086
wait -n $pids 2>/dev/null || wait
