#!/usr/bin/env bash
set -euo pipefail

# wg-render-peers: generate WireGuard [WireGuardPeer] stanzas for a list
# of peer hostnames using OE-WG DNS discovery.
#
# Usage:
#   wg-render-peers hostname1 [hostname2 ...]
#
# For each hostname the tool:
#   1. Resolves AAAA → underlay IP.
#   2. Nibble-reverses the underlay IP.
#   3. Queries <rev>.ip6.routedvpn.com TXT.
#   4. Parses wg-ed25519= → pubkey and mesh= → overlay IP.
#   5. Emits a [WireGuardPeer] stanza.
#
# Output per peer (peer with mesh= record):
#   [WireGuardPeer]
#   # hostname
#   PublicKey=<pubkey>
#   Endpoint=<underlay>:51820
#   AllowedIPs=<overlay>/128
#   PersistentKeepalive=25
#
# If mesh= is absent, AllowedIPs uses the underlay IP instead.
# If port= is present in the TXT record, the Endpoint port is overridden.
#
# Peers whose record has not yet been published are emitted as a comment
# block containing PEER_NOT_YET_PUBLISHED:<hostname>. The script exits
# non-zero (exit 2) after processing ALL peers so that the caller can see
# the full picture before retrying. systemd-networkd will reject a netdev
# containing these marker strings, which is intentional.
#
# Env overrides:
#   WG_RESOLVE_DNS_SERVER   optional; passed to dig as @server
#   WG_RESOLVE_DIG_FLAGS    extra dig flags (default: +short +time=3 +tries=2)
#   WG_LISTEN_PORT          default listen port for peers (default 51820);
#                           overridden per-peer if port= appears in TXT

err() { printf 'wg-render-peers: %s\n' "$*" >&2; }

if [[ $# -lt 1 ]]; then
  err "usage: $0 hostname1 [hostname2 ...]"
  exit 1
fi

if ! command -v python3 >/dev/null 2>&1; then
  err "missing python3"
  exit 1
fi
if ! command -v dig >/dev/null 2>&1 && ! command -v kdig >/dev/null 2>&1; then
  err "missing dig and kdig (install dnsutils or knot-dnsutils)"
  exit 1
fi

dig_cmd=()
if command -v dig >/dev/null 2>&1; then
  dig_cmd=(dig)
else
  dig_cmd=(kdig)
fi
flags=( ${WG_RESOLVE_DIG_FLAGS:-+short +time=3 +tries=2} )

DEFAULT_PORT="${WG_LISTEN_PORT:-51820}"

dig_query() {
  local rtype="$1" name="$2"
  if [[ -n "${WG_RESOLVE_DNS_SERVER:-}" ]]; then
    "${dig_cmd[@]}" "@${WG_RESOLVE_DNS_SERVER}" "${flags[@]}" "$rtype" "$name" 2>/dev/null || true
  else
    "${dig_cmd[@]}" "${flags[@]}" "$rtype" "$name" 2>/dev/null || true
  fi
}

nibble_reverse() {
  python3 - "$1" <<'PY'
import ipaddress, sys
try:
    a = ipaddress.IPv6Address(sys.argv[1])
    print('.'.join(reversed(format(int(a), '032x'))))
except Exception:
    sys.exit(1)
PY
}

# Resolve AAAA for a hostname; prefer non-fdff: global addresses.
resolve_aaaa() {
  local hostname="$1"
  python3 - <<PY 2>/dev/null || true
import ipaddress, sys

raw = """$(dig_query AAAA "$hostname")"""
candidates = []
for line in raw.strip().splitlines():
    line = line.strip().strip('"')
    try:
        a = ipaddress.IPv6Address(line)
        if a.is_global and not str(a).lower().startswith('fdff:'):
            candidates.append(str(a))
    except Exception:
        pass
if candidates:
    print(candidates[0])
else:
    # Fall back to any returned address.
    for line in raw.strip().splitlines():
        line = line.strip().strip('"')
        try:
            ipaddress.IPv6Address(line)
            print(line)
            break
        except Exception:
            pass
PY
}

unresolved=0

for hostname in "$@"; do
  # Step 1: resolve AAAA → underlay IP.
  underlay="$(resolve_aaaa "$hostname")"
  if [[ -z "$underlay" ]]; then
    err "$hostname: no AAAA record found"
    printf '\n# PEER_NOT_YET_PUBLISHED:%s (no AAAA)\n' "$hostname"
    unresolved=$((unresolved + 1))
    continue
  fi

  # Step 2: nibble-reverse.
  nibbles="$(nibble_reverse "$underlay" 2>/dev/null || true)"
  if [[ -z "$nibbles" ]]; then
    err "$hostname: failed to nibble-reverse $underlay"
    printf '\n# PEER_NOT_YET_PUBLISHED:%s (bad underlay IP)\n' "$hostname"
    unresolved=$((unresolved + 1))
    continue
  fi

  # Step 3: query TXT.
  fqdn="${nibbles}.ip6.routedvpn.com"
  raw="$(dig_query TXT "$fqdn")"

  # Step 4: parse wg-ed25519= and optional mesh= / port=.
  pubkey=""
  mesh_ip=""
  port="$DEFAULT_PORT"
  while IFS= read -r line; do
    [[ -z "$line" ]] && continue
    line="${line%\"}"
    line="${line#\"}"
    if [[ "$line" == *wg-ed25519=* ]]; then
      tmp="${line#*wg-ed25519=}"
      pubkey="${tmp%% *}"
      if [[ "$line" == *mesh=* ]]; then
        tmp="${line#*mesh=}"
        mesh_ip="${tmp%% *}"
      fi
      if [[ "$line" == *port=* ]]; then
        tmp="${line#*port=}"
        port="${tmp%% *}"
      fi
      break
    fi
  done <<<"$raw"

  if [[ -z "$pubkey" ]]; then
    err "$hostname: no wg-ed25519 TXT at $fqdn"
    printf '\n# PEER_NOT_YET_PUBLISHED:%s\n' "$hostname"
    unresolved=$((unresolved + 1))
    continue
  fi

  # Validate pubkey shape.
  if ! [[ "$pubkey" =~ ^[A-Za-z0-9+/]{43}=$ ]] || [[ "${pubkey: -2:1}" == "=" ]]; then
    err "$hostname: malformed pubkey at $fqdn: $pubkey"
    printf '\n# PEER_NOT_YET_PUBLISHED:%s (malformed pubkey)\n' "$hostname"
    unresolved=$((unresolved + 1))
    continue
  fi

  # Step 5: emit peer stanza.
  # AllowedIPs: use mesh overlay if present, otherwise use underlay IP.
  if [[ -n "$mesh_ip" ]]; then
    allowed_ips="${mesh_ip}/128"
  else
    allowed_ips="${underlay}/128"
  fi

  printf '\n[WireGuardPeer]\n'
  printf '# %s\n' "$hostname"
  printf 'PublicKey=%s\n' "$pubkey"
  printf 'Endpoint=%s:%s\n' "$underlay" "$port"
  printf 'AllowedIPs=%s\n' "$allowed_ips"
  printf 'PersistentKeepalive=25\n'
done

if [[ "$unresolved" -gt 0 ]]; then
  err "$unresolved peer(s) unresolved; output contains PEER_NOT_YET_PUBLISHED markers"
  exit 2
fi
