#!/bin/bash
# Ensure exchange wire/db helper processes are running (no systemd).
# Root inside taler-exchange container (or host if packages installed there).
#
# Usage:
#   ensure_exchange_helpers.sh
#   ENSURE_ONLY=1 ensure_exchange_helpers.sh   # start missing, no health summary
set -euo pipefail

CONF="${TALER_EXCHANGE_CONFIG:-/etc/taler-exchange/taler-exchange.conf}"
LOG_DIR="${TALER_EXCHANGE_LOG_DIR:-/var/log/taler-exchange}"

if [ "$(id -u)" -ne 0 ]; then
  echo "root only" >&2
  exit 1
fi

mkdir -p "$LOG_DIR"
chmod 755 "$LOG_DIR" 2>/dev/null || true

# Live process under user. Note: Linux COMM is 15 chars — never use pgrep -x
# for long names like taler-exchange-aggregator / taler-exchange-wirewatch.
is_running() {
  local user="$1"
  local bin="$2"
  local base
  base=$(basename "$bin")
  # [t] trick avoids matching this grep/pgrep itself
  ps -u "$user" -o args= 2>/dev/null | grep -qE "(^|/)[${base:0:1}]${base:1}( |$)" \
    || pgrep -u "$user" -f "(^|/)(${base})( |$)" >/dev/null 2>&1
}

# Start with nohup so SIGHUP from parent shell exit does not kill helpers.
start_one() {
  local user="$1"
  local name="$2"
  local bin="$3"
  shift 3
  if is_running "$user" "$bin"; then
    echo "already: $name ($user)"
    return 0
  fi
  echo "start: $name as $user"
  # shellcheck disable=SC2086
  nohup runuser -u "$user" -- "$bin" "$@" >>"$LOG_DIR/${name}.log" 2>&1 </dev/null &
  disown 2>/dev/null || true
  local i
  for i in 1 2 3 4 5 6; do
    sleep 0.4
    if is_running "$user" "$bin"; then
      echo "  ok: $name"
      return 0
    fi
  done
  echo "  FAIL: $name did not stay up (see $LOG_DIR/${name}.log)" >&2
  tail -15 "$LOG_DIR/${name}.log" 2>/dev/null || true
  return 1
}

ec=0
start_one taler-exchange-aggregator taler-exchange-aggregator \
  /usr/bin/taler-exchange-aggregator -c "$CONF" -L INFO || ec=1
start_one taler-exchange-closer taler-exchange-closer \
  /usr/bin/taler-exchange-closer -c "$CONF" -L INFO || ec=1
start_one taler-exchange-wire taler-exchange-wirewatch \
  /usr/bin/taler-exchange-wirewatch -c "$CONF" -L INFO || ec=1
start_one taler-exchange-wire taler-exchange-transfer \
  /usr/bin/taler-exchange-transfer -c "$CONF" -L INFO || ec=1

echo "--- live helpers ---"
ps -eo pid,user,stat,etime,args 2>/dev/null \
  | grep -E 'taler-exchange-(aggregator|closer|wirewatch|transfer)' \
  | grep -vE 'grep| Z |ensure_exchange' || true

exit "$ec"
