#!/bin/bash
# Health check for manual libeufin-bank (same style as merchant/exchange health).
# Container: taler-hacktivism-bank

CONF=/etc/libeufin/libeufin-bank.conf
PORT=$(grep -E '^\s*PORT\s*=' /etc/libeufin/bank-overrides.conf 2>/dev/null | tail -1 | awk -F= '{gsub(/ /,"",$2); print $2}')
PORT=${PORT:-9012}

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; }

echo "=== Taler Bank (libeufin-bank) Health Check ==="

if pgrep -f 'libeufin-bank serve|MainKt serve|tech.libeufin.bank.MainKt' >/dev/null 2>&1; then
  ok "process libeufin-bank serve"
else
  bad "process libeufin-bank serve is NOT running"
fi

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}"
else
  bad "no HTTP response on 127.0.0.1:${PORT}/config"
fi

if curl -sf -m 3 "http://127.0.0.1:${PORT}/taler-integration/config" >/dev/null 2>&1; then
  ok "HTTP /taler-integration/config on 127.0.0.1:${PORT}"
else
  yellow "[WARN] no HTTP response on /taler-integration/config"
fi

if pg_isready >/dev/null 2>&1; then
  ok "postgresql accepting connections"
else
  yellow "[WARN] postgresql not ready (or pg_isready missing)"
fi

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