#!/usr/bin/env bash
# 按推荐顺序启动三所 Flask + 中控 hub/三 agent(PM2).
# 用法(仓库根或任意目录):
#   bash deploy/pm2_start_all.sh
#
# 与 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)"

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}"
  (cd "${proj}" && pm2 start ecosystem.config.cjs)
}

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

start_one crypto_monitor_binance
start_one crypto_monitor_gate
start_one crypto_monitor_okx
start_one manual_trading_hub

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