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

# wg-publish-pubkey: idempotent self-publish of this host's WireGuard
# public key into the routedvpn.com zone tree using the OE-WG TXT format.
#
# Synthesizes the FQDN <nibble-reversed-underlay>.ip6.routedvpn.com from
# this host's underlay (non-fdff:) global IPv6 and POSTs a JSON record to
# the wgkey HTTPS API:
#
#     POST https://wgkey.routedvpn.com/publish
#     {"pubkey":"<base64>","mesh":"<overlay-ipv6>"}
#
# Auth: source-IP checked by server against TLS connection source.
# No client credential or TSIG key needed.
#
# If WG_MESH_IP is set (the host's stable overlay ULA address), the
# request includes "mesh": "<WG_MESH_IP>" for mesh-profile peers.
#
# Idempotent: safe to re-run on every boot or address rotation.
#
# Prerequisites:
#   - /etc/wireguard/wg0.key.pub populated by wireguard-ensure-key
#   - Underlay IPv6 connectivity (SLAAC-derived global address)
#   - curl command available
#   - python3 available (for nibble-reversal)
#
# Env overrides:
#   WG_PUBKEY_FILE          default /etc/wireguard/wg0.key.pub
#   WG_UNDERLAY_INTERFACE   default auto (first non-fdff: global IPv6 found
#                           on any interface). Override to pin a specific
#                           interface when the host has multiple uplinks.
#   WG_MESH_IP              optional; the host's overlay ULA address
#                           (e.g. fdff:ffff:ffff:ffff::54). When set,
#                           included as "mesh" in the JSON body.
#                           Leave unset for general OE-WG hosts with
#                           no mesh overlay.
#   WG_PUBLISH_URL          default https://wgkey.routedvpn.com/publish

WG_PUBKEY_FILE="${WG_PUBKEY_FILE:-/etc/wireguard/wg0.key.pub}"
WG_UNDERLAY_INTERFACE="${WG_UNDERLAY_INTERFACE:-}"
WG_MESH_IP="${WG_MESH_IP:-}"
WG_PUBLISH_URL="${WG_PUBLISH_URL:-https://wgkey.routedvpn.com/publish}"

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

[[ -f "$WG_PUBKEY_FILE" ]] || { err "missing pubkey file: $WG_PUBKEY_FILE"; exit 1; }
command -v curl    >/dev/null 2>&1 || { err "missing curl"; exit 1; }
command -v python3 >/dev/null 2>&1 || { err "missing python3"; exit 1; }

pubkey="$(tr -d '\r\n[:space:]' <"$WG_PUBKEY_FILE")"
[[ -n "$pubkey" ]] || { err "empty pubkey file: $WG_PUBKEY_FILE"; exit 1; }
# WireGuard pubkey shape: 43 base64 chars + single trailing '='.
if ! [[ "$pubkey" =~ ^[A-Za-z0-9+/]{43}=$ ]] || [[ "${pubkey: -2:1}" == "=" ]]; then
  err "invalid wireguard pubkey in $WG_PUBKEY_FILE"
  exit 1
fi

# Publish under the underlay (endpoint) IP, not any overlay mesh IP.
# Peers discover this host by resolving its AAAA → underlay → reverse TXT.
# The mesh field in the request carries the stable overlay IP for
# AllowedIPs; the DNS key itself is always the underlay address.
if [[ -n "$WG_UNDERLAY_INTERFACE" ]]; then
  wgip="$(
    ip -o -6 addr show dev "$WG_UNDERLAY_INTERFACE" scope global 2>/dev/null \
      | awk '$0 !~ /(^|[[:space:]])temporary($|[[:space:]])/ && $0 !~ /(^|[[:space:]])deprecated($|[[:space:]])/ {print $4; exit}' \
      | cut -d/ -f1
  )"
  [[ -n "$wgip" ]] || { err "no global IPv6 on $WG_UNDERLAY_INTERFACE"; exit 1; }
else
  # Auto-detect: first global IPv6 that is not in the fdff::/16 mesh prefix.
  wgip="$(
    ip -o -6 addr scope global 2>/dev/null \
      | awk '$0 !~ /(^|[[:space:]])temporary($|[[:space:]])/ && $0 !~ /(^|[[:space:]])deprecated($|[[:space:]])/ {print $4}' \
      | cut -d/ -f1 \
      | grep -iv '^fdff:' \
      | head -1
  )"
  [[ -n "$wgip" ]] || { err "no underlay global IPv6 found (all addresses in fdff::/16 mesh prefix?)"; exit 1; }
fi

# Build JSON body. pubkey is base64 (A-Za-z0-9+/=), wgip is IPv6 hex+colon,
# WG_MESH_IP is IPv6 hex+colon — none need JSON escaping.
if [[ -n "$WG_MESH_IP" ]]; then
  json_body="$(printf '{"pubkey":"%s","mesh":"%s"}' "$pubkey" "$WG_MESH_IP")"
else
  json_body="$(printf '{"pubkey":"%s"}' "$pubkey")"
fi

http_response="$(
  curl -sS -w '\n%{http_code}' \
    --ipv6 \
    -X POST "$WG_PUBLISH_URL" \
    -H 'Content-Type: application/json' \
    -d "$json_body"
)" || { err "curl failed"; exit 1; }

http_body="${http_response%$'\n'*}"
http_code="${http_response##*$'\n'}"

if [[ "$http_code" != "200" ]]; then
  err "publish failed (HTTP $http_code): $http_body"
  exit 1
fi

printf 'wg-publish-pubkey: published (underlay=%s)\n' "$wgip"
if [[ -n "$WG_MESH_IP" ]]; then
  printf 'wg-publish-pubkey: mesh overlay: %s\n' "$WG_MESH_IP"
fi
