#!/bin/bash
# Health check for manual taler-exchange (same style as check_merchant-health.sh).
# Runnable as taler-exchange-httpd (or any user that can see processes + curl localhost).

CONF=/etc/taler-exchange/taler-exchange.conf
SOCK=/run/taler-exchange/httpd/exchange-http.sock

green()  { echo -e "\e[32m$1\e[0m"; }
red()    { echo -e "\e[31m$1\e[0m"; }
yellow() { echo -e "\e[33m$1\e[0m"; }

fail=0
ok()   { green "[OK] $1"; }
bad()  { red "[FAIL] $1"; fail=1; }
warn() { yellow "[WARN] $1"; }

echo "=== Taler Exchange Health Check ==="

# 1. secmods (started by root base script)
for p in taler-exchange-secmod-rsa taler-exchange-secmod-cs taler-exchange-secmod-eddsa; do
  if pgrep -f "$p" >/dev/null 2>&1; then
    ok "process $p"
  else
    bad "process $p not running"
  fi
done

# 2. httpd
if pgrep -f taler-exchange-httpd >/dev/null 2>&1; then
  ok "process taler-exchange-httpd"
else
  bad "process taler-exchange-httpd is NOT running"
fi

# 3. serving mode
SERVE=$(taler-exchange-config -c "$CONF" -s exchange -o SERVE 2>/dev/null || echo unix)
PORT=$(taler-exchange-config -c "$CONF" -s exchange -o PORT 2>/dev/null || echo 9011)

if [ "$SERVE" = "tcp" ]; then
  if curl -sf -m 3 "http://127.0.0.1:${PORT}/config" >/dev/null 2>&1; then
    ok "HTTP /config on 127.0.0.1:${PORT}"
  elif curl -sf -m 3 "http://127.0.0.1:${PORT}/keys" >/dev/null 2>&1; then
    ok "HTTP /keys on 127.0.0.1:${PORT}"
  else
    bad "no HTTP response on 127.0.0.1:${PORT} (/config|/keys)"
  fi
else
  if [ -S "$SOCK" ]; then
    ok "socket $SOCK"
  else
    bad "socket does NOT exist: $SOCK"
  fi
fi

# 4. wire helpers — ensure (no systemd) then require
if [ "${SKIP_ENSURE:-0}" != "1" ]; then
  if [ -x /usr/local/bin/ensure_exchange_helpers.sh ]; then
    echo "--- ensure_exchange_helpers ---"
    /usr/local/bin/ensure_exchange_helpers.sh || warn "ensure_exchange_helpers exited non-zero"
  elif [ -x "$(dirname "$0")/ensure_exchange_helpers.sh" ]; then
    echo "--- ensure_exchange_helpers ---"
    "$(dirname "$0")/ensure_exchange_helpers.sh" || warn "ensure_exchange_helpers exited non-zero"
  elif [ -x /root/ensure_exchange_helpers.sh ]; then
    echo "--- ensure_exchange_helpers ---"
    /root/ensure_exchange_helpers.sh || warn "ensure_exchange_helpers exited non-zero"
  fi
fi

live_helper() {
  local p="$1"
  # COMM is 15 chars; use full cmdline match
  pgrep -f "(^|/)(${p})( |$)" >/dev/null 2>&1
}

for p in taler-exchange-aggregator taler-exchange-wirewatch taler-exchange-transfer taler-exchange-closer; do
  if live_helper "$p"; then
    ok "process $p"
  else
    bad "process $p not running (settlement needs transfer+aggregator)"
  fi
done

if [ "$fail" -eq 0 ]; then
  green "=== ALL CRITICAL CHECKS PASSED ==="
  exit 0
fi
red "=== SOME CHECKS FAILED ==="
exit 1
