#!/bin/bash
# pg_show_managed.sh — SSH target SHOW 全部 PGAPPLY_WHITELIST param 的當前值，輸出 JSON
#
# 用法：
#   pg_show_managed.sh TARGET
#
# 輸出（stdout）：
#   JSON array [{"name":"...","value":"..."}, ...]，順序 = whitelist 內順序排序後
#
# 用途：
#   admin_machine_spec.php 的 pg_diff_for_resize handler 用此拿 "current values"

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./_lib_pg_apply.sh
source "${SCRIPT_DIR}/_lib_pg_apply.sh"

TARGET="${1:-}"
[[ -z "$TARGET" ]] && { echo "Usage: $0 TARGET" >&2; exit 1; }

raw=$(pgapply_show_managed "$TARGET" 2>/dev/null || true)
[[ -z "$raw" ]] && { echo "SSH 失敗或 PG 無回應：${TARGET}" >&2; exit 2; }

# raw 每行 "name|value"，轉 JSON array
RAW_B64=$(printf '%s' "$raw" | base64 -w0)
python3 - "$RAW_B64" <<'PY'
import base64, json, sys
raw = base64.b64decode(sys.argv[1]).decode("utf-8", "replace")
out = []
for line in raw.splitlines():
    line = line.strip()
    if not line or "|" not in line:
        continue
    name, _, value = line.partition("|")
    out.append({"name": name, "value": value})
print(json.dumps(out))
PY
