#!/bin/bash
# Start wire/db helpers only (root, no interactive shell, no systemd).
# Uses nohup so helpers survive the launching shell.
set -euo pipefail
ROOT=$(cd "$(dirname "$0")" && pwd)
if [ -x "$ROOT/ensure_exchange_helpers.sh" ]; then
  exec "$ROOT/ensure_exchange_helpers.sh"
fi
if [ -x /usr/local/bin/ensure_exchange_helpers.sh ]; then
  exec /usr/local/bin/ensure_exchange_helpers.sh
fi
# Fallback if ensure not installed yet
CONF=/etc/taler-exchange/taler-exchange.conf
LOG_DIR=/var/log/taler-exchange
[ "$(id -u)" -eq 0 ] || { echo "root only"; exit 1; }
mkdir -p "$LOG_DIR"

start_bg() {
  local user="$1"; shift
  local name="$1"; shift
  local bin="$1"
  if pgrep -u "$user" -x "$(basename "$bin")" >/dev/null 2>&1; then
    echo "already: $name"
    return 0
  fi
  echo "start: $name as $user"
  nohup runuser -u "$user" -- "$@" >>"$LOG_DIR/${name}.log" 2>&1 </dev/null &
  disown 2>/dev/null || true
  sleep 0.4
}

start_bg taler-exchange-aggregator taler-exchange-aggregator \
  /usr/bin/taler-exchange-aggregator -c "$CONF" -L INFO
start_bg taler-exchange-closer taler-exchange-closer \
  /usr/bin/taler-exchange-closer -c "$CONF" -L INFO
start_bg taler-exchange-wire taler-exchange-wirewatch \
  /usr/bin/taler-exchange-wirewatch -c "$CONF" -L INFO
start_bg taler-exchange-wire taler-exchange-transfer \
  /usr/bin/taler-exchange-transfer -c "$CONF" -L INFO

sleep 1
pgrep -af 'taler-exchange-(aggregator|closer|wirewatch|transfer|httpd|secmod)' || true
[ -x /usr/local/bin/check_exchange-health.sh ] && /usr/local/bin/check_exchange-health.sh || true
