#!/bin/bash
# Sanity: ensure exchange + merchant helpers are up (no systemd).
# Runs on koopa as root; uses podman into both containers.
set -euo pipefail
ROOT=$(cd "$(dirname "$0")" && pwd)
# shellcheck source=lib.sh
source "$ROOT/lib.sh"
need_root

fail=0
pass() { echo "OK   $1"; }
warn() { echo "WARN $1"; }
bad()  { echo "FAIL $1"; fail=$((fail + 1)); }

EXC_CT="${EXCHANGE_CONTAINER:-taler-hacktivism-exchange-ansible}"
MER_CT="${MERCHANT_CONTAINER:-taler-hacktivism}"

echo "=== ensure + check helpers (no systemd) ==="

# Deploy/ensure scripts if present on host under admin-log mount or /tmp
deploy_into() {
  local ct="$1"
  local src="$2"
  local dst="$3"
  if [ -f "$src" ]; then
    su - hernani -c "podman cp $(printf %q "$src") ${ct}:${dst}" 2>/dev/null \
      || podman cp "$src" "${ct}:${dst}" 2>/dev/null || true
    su - hernani -c "podman exec ${ct} chmod 755 ${dst}" 2>/dev/null || true
  fi
}

ADMIN="${KOOPA_ADMIN_LOG:-/home/hernani/koopa-admin-log}"
# Prefer workspace copy if synced; else scripts next to this file
EX_SCRIPTS="$ROOT/../taler-exchange"
MER_SCRIPTS="$ROOT/../taler-merchant"
[ -d "$ADMIN/scripts/taler-exchange" ] && EX_SCRIPTS="$ADMIN/scripts/taler-exchange"
[ -d "$ADMIN/scripts/taler-merchant" ] && MER_SCRIPTS="$ADMIN/scripts/taler-merchant"

deploy_into "$EXC_CT" "$EX_SCRIPTS/ensure_exchange_helpers.sh" /usr/local/bin/ensure_exchange_helpers.sh
deploy_into "$EXC_CT" "$EX_SCRIPTS/check_exchange-health.sh" /usr/local/bin/check_exchange-health.sh
deploy_into "$MER_CT" "$MER_SCRIPTS/ensure_merchant_helpers.sh" /usr/local/bin/ensure_merchant_helpers.sh
deploy_into "$MER_CT" "$MER_SCRIPTS/check_merchant-health.sh" /usr/local/bin/check_merchant-health.sh

echo "--- exchange container: ensure ---"
if su - hernani -c "podman exec $EXC_CT /usr/local/bin/ensure_exchange_helpers.sh"; then
  pass "exchange helpers ensure"
else
  bad "exchange helpers ensure failed"
fi

echo "--- merchant container: ensure ---"
if su - hernani -c "podman exec $MER_CT /usr/local/bin/ensure_merchant_helpers.sh"; then
  pass "merchant helpers ensure"
else
  bad "merchant helpers ensure failed"
fi

echo "--- process presence ---"
check_ct_proc() {
  local ct="$1"
  local p="$2"
  # COMM is 15 chars — match full cmdline
  if su - hernani -c "podman exec $ct pgrep -f '(^|/)${p}( |$)'" >/dev/null 2>&1; then
    pass "$ct: $p"
  else
    bad "$ct: $p missing"
  fi
}

for p in taler-exchange-httpd taler-exchange-aggregator taler-exchange-transfer \
         taler-exchange-wirewatch taler-exchange-closer; do
  check_ct_proc "$EXC_CT" "$p"
done
for p in taler-merchant-httpd taler-merchant-wirewatch taler-merchant-depositcheck \
         taler-merchant-webhook taler-merchant-kyccheck \
         taler-merchant-exchangekeyupdate taler-merchant-reconciliation; do
  check_ct_proc "$MER_CT" "$p"
done

echo "=== summary fails=$fail ==="
exit "$fail"
