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

# wg-connect: operator one-shot tool to add an OE-WG peer to a running
# WireGuard interface.
#
# Usage:
#   wg-connect <hostname> [wg-interface]
#
# The tool:
#   1. Resolves <hostname> AAAA → underlay IP.
#   2. Nibble-reverses the underlay IP.
#   3. Queries <rev>.ip6.routedvpn.com TXT for the OE-WG record.
#   4. Parses wg-ed25519= → pubkey, and optionally mesh= and port=.
#   5. Runs: wg set <iface> peer <pubkey> \
#              endpoint <underlay>:<port> \
#              allowed-ips <mesh-or-underlay>/128 \
#              persistent-keepalive 25
#   6. Prints a summary of what was done.
#
# If mesh= is present in the TXT record, the overlay IP is used for
# AllowedIPs. Otherwise the underlay IP is used.
#
# Prerequisites:
#   - wg (wireguard-tools) installed and in PATH
#   - dig or kdig (dnsutils or knot-dnsutils)
#   - python3
#   - Sufficient privileges to run `wg set` (typically root or CAP_NET_ADMIN)
#
# 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)

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

if [[ $# -lt 1 || $# -gt 2 ]]; then
  err "usage: $0 <hostname> [wg-interface]"
  exit 1
fi

hostname="$1"
iface="${2:-wg0}"

# Dependency checks.
if ! command -v wg >/dev/null 2>&1; then
  err "missing wg command (install wireguard-tools)"
  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} )

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
}

# Step 1: resolve AAAA → underlay IP; prefer non-fdff: global addresses.
aaaa_raw="$(dig_query AAAA "$hostname")"
underlay="$(
  python3 - <<PY 2>/dev/null || true
import ipaddress, sys

raw = """$aaaa_raw"""
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:
    for line in raw.strip().splitlines():
        line = line.strip().strip('"')
        try:
            ipaddress.IPv6Address(line)
            print(line)
            break
        except Exception:
            pass
PY
)"
if [[ -z "$underlay" ]]; then
  err "could not resolve AAAA for $hostname"
  exit 1
fi

# Step 2: nibble-reverse.
nibbles="$(
  python3 - "$underlay" <<'PY'
import ipaddress, sys
try:
    a = ipaddress.IPv6Address(sys.argv[1])
    print('.'.join(reversed(format(int(a), '032x'))))
except Exception:
    sys.exit(1)
PY
)"
if [[ -z "$nibbles" ]]; then
  err "failed to nibble-reverse $underlay"
  exit 1
fi

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

# Step 4: parse wg-ed25519=, optional mesh=, optional port=.
pubkey=""
mesh_ip=""
port="51820"
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 "no wg-ed25519 TXT at $fqdn ($hostname has not published an OE-WG record)"
  exit 2
fi

# Validate pubkey shape.
if ! [[ "$pubkey" =~ ^[A-Za-z0-9+/]{43}=$ ]] || [[ "${pubkey: -2:1}" == "=" ]]; then
  err "malformed pubkey from $fqdn: $pubkey"
  exit 1
fi

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

# Step 5: add the peer.
wg set "$iface" peer "$pubkey" \
  endpoint "${underlay}:${port}" \
  allowed-ips "$allowed_ips" \
  persistent-keepalive 25

# Step 6: print summary.
printf 'wg-connect: added peer %s to %s\n' "$hostname" "$iface"
printf 'wg-connect: pubkey       %s\n' "$pubkey"
printf 'wg-connect: endpoint     %s:%s\n' "$underlay" "$port"
printf 'wg-connect: allowed-ips  %s\n' "$allowed_ips"
