#!/bin/bash
set -euo pipefail

WG_KEY_PUB="${WG_KEY_PUB:-/etc/wireguard/wg0.pub}"
WG_ENDPOINT="${WG_ENDPOINT:-https://wgkey.routedvpn.com}"

if [[ ! -f "$WG_KEY_PUB" ]]; then
  echo "ERROR: WireGuard public key not found at $WG_KEY_PUB" >&2
  exit 1
fi

pubkey="$(tr -d '[:space:]' < "$WG_KEY_PUB")"

if [[ ${#pubkey} -ne 44 ]]; then
  echo "ERROR: unexpected pubkey length (${#pubkey}), expected 44" >&2
  exit 1
fi

echo "Publishing WireGuard public key to ${WG_ENDPOINT}/pubkey ..."

response="$(curl -fsSL \
  --max-time 15 \
  -X POST \
  -H "Content-Type: text/plain" \
  --data-raw "$pubkey" \
  "${WG_ENDPOINT}/pubkey")"

echo "Response: $response"

name="$(printf '%s' "$response" | grep -o '"name":"[^"]*"' | cut -d'"' -f4 || true)"
if [[ -n "$name" ]]; then
  echo "Published to: $name"
fi
