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

set -u

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

  (default)   Start merchant helpers + httpd.
  --restart   Stop live taler-merchant-* daemons, then start cleanly.
              Does not touch postgres/nginx.
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-merchant-httpd" ]; then
  echo "This script must be run as user taler-merchant-httpd" >&2
  exit 1
fi

list_merchant_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_merchant.sh*) continue ;;
    esac
    case "$args" in
      *taler-merchant-httpd\ *|taler-merchant-httpd\ *)
        echo "$pid" ;;
      *taler-merchant-webhook*|*taler-merchant-kyccheck*|*taler-merchant-wirewatch*)
        echo "$pid" ;;
      *taler-merchant-depositcheck*|*taler-merchant-exchangekeyupdate*|*taler-merchant-reconciliation*)
        echo "$pid" ;;
    esac
  done | sort -u
}

kill_taler_merchant() {
  local pids
  pids=$(list_merchant_pids | tr '\n' ' ')
  if [ -z "${pids// }" ]; then
    echo "No live taler-merchant 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_merchant_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-merchant daemons stopped."
}

TIMESTAMP=$(date +"%Y%m%d_%H%M")
BACKUP_DIR="/var/taler-backups"
LOG_DIR="/var/log/taler-merchant"

if [ "$DO_RESTART" -eq 1 ]; then
  echo "=== restart: kill taler-merchant-* ==="
  kill_taler_merchant
fi

BACKUP_NAME="taler-merchant-$TIMESTAMP.sql"
echo -n "Backup taler-merchant DB: "
mkdir -p "$BACKUP_DIR" 2>/dev/null || true
if pg_dump taler-merchant >"$BACKUP_DIR/$BACKUP_NAME" 2>/dev/null; then
  echo "OK"
else
  echo "SKIP/FAIL (postgres?)"
fi
echo "Start taler-merchant components:"

LOG_FILE="$LOG_DIR/taler-merchant-httpd-$(date +%Y-%m-%d).log"
mkdir -p "$LOG_DIR"
touch "$LOG_FILE"

# Prefer dedicated ensure script (nohup + logs per helper).
if [ -x /usr/local/bin/ensure_merchant_helpers.sh ]; then
  /usr/local/bin/ensure_merchant_helpers.sh || true
elif [ -x "$(dirname "$0")/ensure_merchant_helpers.sh" ]; then
  "$(dirname "$0")/ensure_merchant_helpers.sh" || true
else
  nohup taler-merchant-httpd --log=info >>"$LOG_FILE" 2>&1 </dev/null &
  disown 2>/dev/null || true
  sleep 2
  nohup taler-merchant-webhook >>"$LOG_DIR/taler-merchant-webhook.log" 2>&1 </dev/null &
  nohup taler-merchant-kyccheck >>"$LOG_DIR/taler-merchant-kyccheck.log" 2>&1 </dev/null &
  nohup taler-merchant-wirewatch -c /etc/taler-merchant/taler-merchant.conf -L INFO \
    >>"$LOG_DIR/taler-merchant-wirewatch.log" 2>&1 </dev/null &
  nohup taler-merchant-depositcheck >>"$LOG_DIR/taler-merchant-depositcheck.log" 2>&1 </dev/null &
  nohup taler-merchant-exchangekeyupdate >>"$LOG_DIR/taler-merchant-exchangekeyupdate.log" 2>&1 </dev/null &
  nohup taler-merchant-reconciliation >>"$LOG_DIR/taler-merchant-reconciliation.log" 2>&1 </dev/null &
  disown 2>/dev/null || true
  sleep 1
fi

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

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