#!/usr/bin/env bash
# wg21-join/status — outputs {"mgmtPublicKey":<key|null>,"mgmtAddress":<addr|null>,"up":<bool>}, or
# {"managed":false} when wg21 is absent or owned by another role (no marker): nothing is reported then.
set -euo pipefail
cat >/dev/null
WGDIR="${SSR_ETC:-/etc}/wireguard"
if [ ! -f "$WGDIR/wg21.conf" ] || ! grep -qxF '# managed-by: silvershell wg21-join' "$WGDIR/wg21.conf"; then
  echo '{"managed":false}' > "$SSR_OUTPUTS"; exit 0
fi
pub=""; addr=""
if [ -s "$WGDIR/mgmt_private.key" ]; then pub=$(wg pubkey < "$WGDIR/mgmt_private.key" 2>/dev/null || true); fi
addr=$(sed -n 's#^Address *= *\([0-9.]*\)/.*#\1#p' "$WGDIR/wg21.conf" | head -n 1)
up=false; if wg show wg21 >/dev/null 2>&1; then up=true; fi
jq -n --arg k "$pub" --arg a "$addr" --argjson u "$up" \
  '{managed:true,mgmtPublicKey:(if $k=="" then null else $k end),mgmtAddress:(if $a=="" then null else $a end),up:$u}' > "$SSR_OUTPUTS"
