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

# wg-resolve-pubkey: resolve a WireGuard peer's public key and optional
# mesh overlay address from routedvpn.com using the OE-WG TXT format.
#
# Usage:
#   wg-resolve-pubkey <ipv6-address-or-hostname>
#
# Input can be:
#   - An IPv6 address (underlay): nibble-reversed directly and queried.
#   - A hostname: AAAA record resolved first to get the underlay IP,
#     then the reverse TXT is queried.
#
# Looks up TXT at <nibble-reversed-underlay>.ip6.routedvpn.com, parses
# the `wg-ed25519=<base64>` payload, and prints:
#   line 1: the public key
#   line 2: the mesh overlay IP (from mesh= field), or empty line if absent
#
# Exit 0  : pubkey printed on stdout (mesh IP on line 2, may be empty)
# Exit 2  : TXT record absent / not yet published. Prints a placeholder
#           of the form PEER_NOT_YET_PUBLISHED:<input> so the caller can
#           leave a non-empty marker in rendered output and re-run after
#           the missing peer publishes.
# Exit 1  : real error (dig/kdig missing, malformed input, hostname
#           resolution failure, etc.)
#
# Env overrides:
#   WG_RESOLVE_DNS_SERVER  optional `@server` for dig (default: system
#                          resolver — picks up routedvpn.com via the
#                          public NS records)
#   WG_RESOLVE_DIG_FLAGS   extra dig flags (default: +short +time=3 +tries=2)

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

if [[ $# -ne 1 ]]; then
  err "usage: $0 <ipv6-address-or-hostname>"
  exit 1
fi

input="$1"

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} )

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
}

# Determine if input is an IPv6 address or a hostname. python3's
# ipaddress module validates; if it raises, treat as hostname.
wgip="$(
  python3 - "$input" <<'PY' 2>/dev/null || true
import ipaddress, sys
try:
    a = ipaddress.IPv6Address(sys.argv[1])
    print(str(a))
except Exception:
    pass
PY
)"

if [[ -z "$wgip" ]]; then
  # Input is a hostname — resolve AAAA first.
  aaaa_raw="$(dig_query AAAA "$input")"
  # dig +short AAAA may return multiple lines; pick the first global
  # non-fdff: address, falling back to the first result.
  wgip="$(
    python3 - <<PY 2>/dev/null || true
import ipaddress, sys

lines = """$aaaa_raw""".strip().splitlines()
candidates = []
for line in lines:
    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])
elif lines:
    # Fall back to first returned address.
    first = lines[0].strip().strip('"')
    try:
        ipaddress.IPv6Address(first)
        print(first)
    except Exception:
        pass
PY
  )"
  if [[ -z "$wgip" ]]; then
    err "could not resolve AAAA for hostname: $input"
    printf 'PEER_NOT_YET_PUBLISHED:%s\n' "$input"
    exit 2
  fi
fi

# Validate + nibble-reverse via python's ipaddress (also normalises
# shorthand like "2001:db8::1").
nibbles="$(
  python3 - "$wgip" <<'PY' 2>/dev/null || true
import ipaddress, sys
try:
    a = ipaddress.IPv6Address(sys.argv[1])
except Exception:
    sys.exit(1)
print('.'.join(reversed(format(int(a), '032x'))))
PY
)"
if [[ -z "$nibbles" ]]; then
  err "not a valid IPv6 address: $wgip"
  exit 1
fi

fqdn="${nibbles}.ip6.routedvpn.com"

# `dig +short TXT` returns one quoted string per line. Strip quotes and
# scan for the wg-ed25519= tag.
raw="$(dig_query TXT "$fqdn")"

pubkey=""
mesh_ip=""
while IFS= read -r line; do
  [[ -z "$line" ]] && continue
  # Strip surrounding quotes that dig +short emits.
  line="${line%\"}"
  line="${line#\"}"
  # Look for wg-ed25519= tag anywhere in the record value.
  if [[ "$line" == *wg-ed25519=* ]]; then
    # Extract pubkey: everything after wg-ed25519= up to next space or end.
    tmp="${line#*wg-ed25519=}"
    pubkey="${tmp%% *}"
    # Extract mesh= if present.
    if [[ "$line" == *mesh=* ]]; then
      tmp="${line#*mesh=}"
      mesh_ip="${tmp%% *}"
    fi
    break
  fi
done <<<"$raw"

if [[ -z "$pubkey" ]]; then
  err "no wg-ed25519 TXT at $fqdn (peer not yet published?)"
  printf 'PEER_NOT_YET_PUBLISHED:%s\n' "$input"
  exit 2
fi

# Validate shape: 43 base64 chars + trailing '=', last-but-one not '='.
if ! [[ "$pubkey" =~ ^[A-Za-z0-9+/]{43}=$ ]] || [[ "${pubkey: -2:1}" == "=" ]]; then
  err "malformed pubkey from $fqdn: $pubkey"
  printf 'PEER_NOT_YET_PUBLISHED:%s\n' "$input"
  exit 2
fi

printf '%s\n' "$pubkey"
printf '%s\n' "$mesh_ip"
