#!/usr/bin/env bash
# 按推荐顺序启动三所 Flask + 中控 hub/三 agent(PM2).
# 用法(仓库根或任意目录):
#   bash deploy/pm2_start_all.sh
#   bash deploy/pm2_start_all.sh --only okx
#   bash deploy/pm2_start_all.sh --only binance
#   bash deploy/pm2_start_all.sh --only gate
#
# 与 deploy/setup_env.sh 独立:setup_env 只建 venv;本脚本负责 PM2 启动.
set -e
set -u
if [ -n "${BASH_VERSION:-}" ]; then
  set -o pipefail
fi

DEPLOY_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${DEPLOY_DIR}/.." && pwd)"
# shellcheck source=lib/common.sh
source "${DEPLOY_DIR}/lib/common.sh"

ONLY="all"
while [[ $# -gt 0 ]]; do
  case "$1" in
    --only)
      ONLY="${2:-all}"
      shift 2
      ;;
    -h|--help)
      sed -n '2,10p' "$0" | sed 's/^# \?//'
      exit 0
      ;;
    *)
      echo "未知参数: $1" >&2
      exit 1
      ;;
  esac
done

start_one() {
  local dir_name="$1"
  local proj="${REPO_ROOT}/${dir_name}"
  local eco="${proj}/ecosystem.config.cjs"
  if [[ ! -f "${eco}" ]]; then
    echo "skip (no ecosystem): ${dir_name}" >&2
    return 0
  fi
  echo "==> pm2 start ${dir_name}"
  # 已存在则 restart,避免重复 start 导致 set -e 退出
  if (cd "${proj}" && pm2 start ecosystem.config.cjs); then
    return 0
  fi
  echo "  (已存在,改为 restart)"
  (cd "${proj}" && pm2 startOrReload ecosystem.config.cjs --update-env) \
    || (cd "${proj}" && pm2 reload ecosystem.config.cjs --update-env) \
    || true
}

if ! command -v pm2 >/dev/null 2>&1; then
  echo "未找到 pm2,请先安装 Node.js 与 pm2(见 docs/ubuntu-server.md)" >&2
  exit 1
fi

if [[ "${ONLY}" == "all" ]]; then
  start_one crypto_monitor_binance
  start_one crypto_monitor_gate
  start_one crypto_monitor_okx
  start_one manual_trading_hub
else
  ex_key="$(normalize_exchange_key "${ONLY}" || true)"
  if [[ -z "${ex_key}" ]]; then
    echo "未知 --only 值: ${ONLY} (期望 okx|binance|gate|all)" >&2
    exit 1
  fi
  dir_name="$(exchange_dir "${ex_key}")"
  start_one "${dir_name}"
fi

pm2 save 2>/dev/null || true
echo ""
echo "PM2 进程:"
pm2 list
