#!/bin/bash
# Start / restart taler-exchange-httpd (manual, no systemd).
# Run as: taler-exchange-httpd
# Same role as start_merchant.sh for the merchant.
#
# Usage:
#   start_exchange.sh
#   start_exchange.sh --restart | -r
#   start_exchange.sh --help

set -u

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

  (default)   Start taler-exchange-httpd if not already running.
  --restart   Stop live taler-exchange-httpd, then start cleanly.
              Does not touch postgres/secmods/wire helpers
              (those come from /root/start_base_services_for_taler_exchange.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)" != "taler-exchange-httpd" ]; then
  echo "This script must be run as user taler-exchange-httpd" >&2
  exit 1
fi

CONF=/etc/taler-exchange/taler-exchange.conf
LOG_DIR=/var/log/taler-exchange
PORT=$(taler-exchange-config -c "$CONF" -s exchange -o PORT 2>/dev/null || echo 9011)

list_httpd_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_exchange.sh*) continue ;;
    esac
    case "$args" in
      *taler-exchange-httpd\ *|taler-exchange-httpd\ *|/usr/bin/taler-exchange-httpd\ *)
        echo "$pid"
        ;;
    esac
  done | sort -u
}

kill_httpd() {
  local pids
  pids=$(list_httpd_pids | tr '\n' ' ')
  if [ -z "${pids// }" ]; then
    echo "No live taler-exchange-httpd processes 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_httpd_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 "taler-exchange-httpd stopped."
}

if [ "$DO_RESTART" -eq 1 ]; then
  echo "=== restart: kill taler-exchange-httpd ==="
  kill_httpd
fi

echo "Start taler-exchange-httpd:"
LOG_FILE="$LOG_DIR/taler-exchange-httpd-$(date +%Y-%m-%d).log"
mkdir -p "$LOG_DIR"
touch "$LOG_FILE" 2>/dev/null || true

if [ "$DO_RESTART" -eq 0 ] && [ -n "$(list_httpd_pids)" ]; then
  echo "taler-exchange-httpd already running"
else
  nohup taler-exchange-httpd -c "$CONF" -L INFO >>"$LOG_FILE" 2>&1 &
  disown 2>/dev/null || true
  sleep 2
fi

echo "Live processes:"
ps -eo pid,stat,args 2>/dev/null | grep taler-exchange-httpd | grep -v grep | grep -v ' Z ' || true

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