#!/bin/bash
# Sanity: exchange can read bank wire gateway (bearer + public URL).
# Run on koopa as root (needs /root/bank-exchange-password.txt + podman).
set -euo pipefail
ROOT=$(cd "$(dirname "$0")" && pwd)
# shellcheck source=lib.sh
source "$ROOT/lib.sh"
need_root

echo "=== Exchange wirewatch / wire gateway ==="

if ! read_pw EPW /root/bank-exchange-password.txt; then
  fail "missing /root/bank-exchange-password.txt"
  exit 1
fi

ET=$(bank_token exchange "$EPW")
if [ -z "$ET" ]; then
  fail "could not get bank token for exchange user"
  exit 1
fi
pass "bank token for exchange user"

# History must work with Bearer (Basic is rejected by libeufin on history)
tmp=$(mktemp)
code=$(curl -sk -m 15 -o "$tmp" -w '%{http_code}' \
  -H "Authorization: Bearer ${ET}" \
  "${BANK_PUBLIC}/accounts/exchange/taler-wire-gateway/history/incoming?delta=-10")
if [ "$code" = "200" ]; then
  pass "wire gateway history via ${BANK_PUBLIC} (HTTP $code)"
  python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print("  incoming_count", len(d.get("incoming_transactions") or []))' "$tmp"
else
  # fallback local
  code2=$(curl -sS -m 15 -o "$tmp" -w '%{http_code}' \
    -H "Authorization: Bearer ${ET}" \
    "${BANK_URL}/accounts/exchange/taler-wire-gateway/history/incoming?delta=-10")
  if [ "$code2" = "200" ]; then
    warn "public wire gateway HTTP $code; local BANK_URL OK ($code2) — check DNS/hosts in exchange container"
  else
    fail "wire gateway history public=$code local=$code2"
  fi
fi
rm -f "$tmp"

# Basic must fail on history (documents expected auth mode)
code_b=$(curl -sk -m 10 -o /dev/null -w '%{http_code}' \
  -u "exchange:${EPW}" \
  "${BANK_URL}/accounts/exchange/taler-wire-gateway/history/incoming?delta=-5")
if [ "$code_b" = "401" ]; then
  pass "Basic auth correctly rejected on history ($code_b) — use bearer TOKEN"
else
  warn "Basic on history returned $code_b (expected 401)"
fi

# Container credential + wirewatch process
if su - hernani -c 'podman exec taler-hacktivism-exchange-ansible true' 2>/dev/null; then
  su - hernani -c 'podman exec taler-hacktivism-exchange-ansible bash -c "
    set +e
    echo \"--- secret (redacted) ---\"
    if [ -r /etc/taler-exchange/secrets/exchange-accountcredentials-1.secret.conf ]; then
      sed \"s/secret-token:.*/secret-token:***/; s/^TOKEN = .*/TOKEN = ***/; s/^PASSWORD = .*/PASSWORD = ***/\" \
        /etc/taler-exchange/secrets/exchange-accountcredentials-1.secret.conf
    else
      # root-only file: cat as root via outer exec
      true
    fi
    echo \"--- hosts bank ---\"
    grep bank.hacktivism.ch /etc/hosts || echo \"(no hosts pin)\"
    echo \"--- wirewatch ---\"
    ps -eo pid,stat,args | grep \"[w]irewatch\" || echo \"(no wirewatch process)\"
  "' 2>&1 || warn "podman exec exchange failed"

  AUTH_METHOD=$(su - hernani -c 'podman exec -u root taler-hacktivism-exchange-ansible \
    grep -E "^WIRE_GATEWAY_AUTH_METHOD" /etc/taler-exchange/secrets/exchange-accountcredentials-1.secret.conf' 2>/dev/null | awk '{print $3}')
  GW_URL=$(su - hernani -c 'podman exec -u root taler-hacktivism-exchange-ansible \
    grep -E "^WIRE_GATEWAY_URL" /etc/taler-exchange/secrets/exchange-accountcredentials-1.secret.conf' 2>/dev/null | awk '{print $3}')
  info "WIRE_GATEWAY_URL=$GW_URL"
  info "WIRE_GATEWAY_AUTH_METHOD=$AUTH_METHOD"
  if [ "$AUTH_METHOD" = "bearer" ]; then pass "auth method bearer"
  else fail "auth method is '$AUTH_METHOD' (want bearer + TOKEN=)"
  fi
  case "$GW_URL" in
    https://bank.hacktivism.ch/*) pass "gateway uses public bank URL" ;;
    http://127.*|http://host.containers*) warn "gateway uses local URL: $GW_URL" ;;
    *) warn "unexpected gateway URL: $GW_URL" ;;
  esac
else
  warn "exchange container not reachable via podman"
fi

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