#!/bin/bash
# Sanity: public + local Taler endpoints respond (GOA stack).
# Run on koopa as root (or any user with network to services).
set -euo pipefail
ROOT=$(cd "$(dirname "$0")" && pwd)
# shellcheck source=lib.sh
source "$ROOT/lib.sh"

echo "=== Taler stack health ==="

# Public HTTPS (via Caddy / VeciGate)
for url in \
  "${EXCHANGE_PUBLIC}/config" \
  "${EXCHANGE_PUBLIC}/keys" \
  "${BANK_PUBLIC}/config" \
  "${MERCHANT_PUBLIC}/config"
do
  code=$(http_code "$url")
  if [ "$code" = "200" ]; then pass "$url -> $code"
  else fail "$url -> $code"
  fi
done

# Local loopback ports (containers via pasta)
for spec in \
  "bank ${BANK_URL}/config" \
  "merchant ${MERCHANT_URL}/config" \
  "exchange-via-public ${EXCHANGE_PUBLIC}/config"
do
  name=${spec%% *}
  url=${spec#* }
  code=$(http_code "$url")
  if [ "$code" = "200" ]; then pass "local $name -> $code"
  else fail "local $name -> $code"
  fi
done

# Merchant multi-currency
tmp=$(mktemp)
curl -sk -m 12 -o "$tmp" "${MERCHANT_PUBLIC}/config" || true
if python3 - "$tmp" <<'PY'
import json,sys
d=json.load(open(sys.argv[1]))
ex=[e.get("currency") for e in d.get("exchanges") or []]
cur=list((d.get("currencies") or {}).keys())
ok = "GOA" in ex and "CHF" in ex and "GOA" in cur
print("currency_default", d.get("currency"))
print("exchanges", ex)
print("currencies", cur)
sys.exit(0 if ok else 1)
PY
then pass "merchant has CHF + GOA exchanges"
else fail "merchant missing CHF/GOA in /config"
fi
rm -f "$tmp"

# Exchange currency GOA
tmp=$(mktemp)
curl -sk -m 12 -o "$tmp" "${EXCHANGE_PUBLIC}/config" || true
if python3 - "$tmp" <<'PY'
import json,sys
d=json.load(open(sys.argv[1]))
c=(d.get("currency") or d.get("currency_specification",{}).get("currency"))
print("exchange_currency", c)
sys.exit(0 if c=="GOA" else 1)
PY
then pass "exchange currency GOA"
else fail "exchange currency not GOA"
fi
rm -f "$tmp"

echo "=== summary fails=$FAILS ==="
exit "$FAILS"
