#!/usr/bin/env bash
# dns-records.sh — print the DNS records to configure on YOUR party DNS server.
#
# Usage: tooling/dns-records.sh [online|airgap]   (default: airgap)
#   online  service names only — your DNS forwards everything else to the internet
#   airgap  service names + the spoofed upstream hosts (Mojang/launcher/NeoForge),
#           so guest laptops fetch game files from the LAN mirror with no internet
#
# All names point to HOST_LAN_IP. Reads BASE_DOMAIN / HOST_LAN_IP from .env.
# Prints several formats; use whichever your DNS UI wants.
set -euo pipefail
cd "$(dirname "$0")/.."

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

mode="${1:-airgap}"

# Stack service names (always).
services=(
  "${BASE_DOMAIN}"
  "auth.${BASE_DOMAIN}"
  "packwiz.${BASE_DOMAIN}"
  "mc.${BASE_DOMAIN}"
)

# Upstream hosts spoofed onto the LAN mirror (AIRGAP only). Keep in sync with
# caddy/conf.d/20-mirror.caddy and docker-compose.mirror.yml.
spoof=(
  "meta.prismlauncher.org"
  "piston-meta.mojang.com"
  "piston-data.mojang.com"
  "libraries.minecraft.net"
  "maven.neoforged.net"
  "resources.download.minecraft.net"
)

names=("${services[@]}")
case "$mode" in
  online) ;;
  airgap) names+=("${spoof[@]}") ;;
  *) echo "usage: $0 [online|airgap] [hosts]" >&2; exit 1 ;;
esac

# Marker so /etc/hosts edits can be applied/removed cleanly.
MARK="ulicraft ${mode}"

# `hosts` format: print ONLY the /etc/hosts block (marker-wrapped) so it can be
# piped straight into /etc/hosts to simulate the party DNS. See README.
if [ "${2:-}" = hosts ]; then
  echo "# >>> ${MARK} >>>"
  for n in "${names[@]}"; do printf '%s %s\n' "$HOST_LAN_IP" "$n"; done
  echo "# <<< ${MARK} <<<"
  exit 0
fi

echo "# DNS records for mode=${mode}  ->  ${HOST_LAN_IP}"
echo "# Configure these on your party DNS server (all A records to the host)."
echo

echo "## Plain (name  ->  ip)"
for n in "${names[@]}"; do printf '%-36s %s\n' "$n" "$HOST_LAN_IP"; done
echo

echo "## hosts file (/etc/hosts style)"
for n in "${names[@]}"; do printf '%s %s\n' "$HOST_LAN_IP" "$n"; done
echo

echo "## BIND zone (A records)"
for n in "${names[@]}"; do printf '%-36s IN A   %s\n' "${n}." "$HOST_LAN_IP"; done
echo

echo "## dnsmasq (address=)"
echo "address=/${BASE_DOMAIN}/${HOST_LAN_IP}   # wildcard covers all *.${BASE_DOMAIN}"
if [ "$mode" = airgap ]; then
  for n in "${spoof[@]}"; do printf 'address=/%s/%s\n' "$n" "$HOST_LAN_IP"; done
fi
echo

echo "## Minecraft (no port needed)"
echo "# Clients connect to  mc.${BASE_DOMAIN}  (defaults to :25565)."
echo "# Optional SRV if your DNS supports it:"
echo "_minecraft._tcp.mc.${BASE_DOMAIN}.  IN SRV  0 0 25565 mc.${BASE_DOMAIN}."
