#!/bin/bash
# Start / restart libeufin-bank serve (manual, no systemd).
# Run as: libeufin-bank
# Same role as start_merchant.sh / start_exchange.sh.
#
# Container: taler-hacktivism-bank
# Prerequisite: /root/start_base_services_for_taler_bank.sh (as root) for postgres.
#
# Usage:
#   start_bank.sh
#   start_bank.sh --restart | -r
#   start_bank.sh --help

set -u

usage() {
  cat <<'EOF'
Usage: start_bank.sh [--restart|-r] [--help|-h]

  (default)   Start libeufin-bank serve if not already running.
  --restart   Stop live serve process, then start cleanly.
              Does not touch postgres (use /root/start_base_services_for_taler_bank.sh).
EOF
}

DO_RESTART=0
for arg in "$@"; do
  case "$arg" in
    --restart|-r) DO_RESTART=1 ;;
    --help|-h) usage; exit 0 ;;
    *) echo "Unknown option: $arg" >&2; usage >&2; exit 2 ;;
  esac
done

if [ "$(id -un)" != "libeufin-bank" ]; then
  echo "This script must be run as user libeufin-bank" >&2
  exit 1
fi

CONF=/etc/libeufin/libeufin-bank.conf
LOG_DIR=/var/log/libeufin-bank
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}

# Match both wrapper name and the Java MainKt process that actually listens.
list_serve_pids() {
  ps -eo pid=,stat=,args= 2>/dev/null | while read -r pid stat args; do
    case "$stat" in Z*) continue ;; esac
    case "$args" in
      *start_bank.sh*) continue ;;
      *check_bank-health*) continue ;;
    esac
    case "$args" in
      *libeufin-bank\ serve*|/usr/bin/libeufin-bank\ serve*|*MainKt\ serve*|*tech.libeufin.bank.MainKt*)
        echo "$pid"
        ;;
    esac
  done | sort -u
}

kill_serve() {
  local pids
  pids=$(list_serve_pids | tr '\n' ' ')
  if [ -z "${pids// }" ]; then
    echo "No live libeufin-bank serve to stop."
    return 0
  fi
  echo "Stopping PIDs: $pids"
  # shellcheck disable=SC2086
  kill -TERM $pids 2>/dev/null || true
  sleep 2
  local left
  left=$(list_serve_pids | tr '\n' ' ')
  if [ -n "${left// }" ]; then
    echo "SIGKILL remaining: $left"
    # shellcheck disable=SC2086
    kill -KILL $left 2>/dev/null || true
    sleep 1
  fi
  echo "libeufin-bank serve stopped."
}

if [ "$DO_RESTART" -eq 1 ]; then
  echo "=== restart: kill libeufin-bank serve ==="
  kill_serve
fi

echo "Start libeufin-bank serve (port $PORT):"
LOG_FILE="$LOG_DIR/libeufin-bank-$(date +%Y-%m-%d).log"
mkdir -p "$LOG_DIR"
touch "$LOG_FILE" 2>/dev/null || true

if [ "$DO_RESTART" -eq 0 ] && [ -n "$(list_serve_pids)" ]; then
  echo "libeufin-bank serve already running"
else
  nohup libeufin-bank serve -c "$CONF" >>"$LOG_FILE" 2>&1 &
  disown 2>/dev/null || true
  sleep 2
fi

echo "Live processes:"
ps -eo pid,stat,args 2>/dev/null | grep -E 'libeufin-bank serve|MainKt serve' | grep -v grep | grep -v ' Z ' || true

if [ -x /usr/local/bin/check_bank-health.sh ]; then
  /usr/local/bin/check_bank-health.sh || exit 1
elif [ -x ./check_bank-health.sh ]; then
  ./check_bank-health.sh || exit 1
fi
exit 0
