#!/usr/bin/env bash
# 仅子代理 PM2(中控请用 scripts/pm2_hub.sh 或 ecosystem.config.cjs 一次起全部)
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
HUB_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
ECO="${HUB_DIR}/ecosystem.agents.config.cjs"

usage() {
  cat <<'EOF'
用法: bash scripts/pm2_agents.sh <start|stop|restart|status|logs|delete>

  一般请用: bash scripts/pm2_hub.sh start   (hub + agent 一起)

  本脚本仅操作 3 路子代理(不含中控)

仅启动币安: pm2 start ecosystem.agents.config.cjs --only manual-agent-binance
EOF
}

cmd="${1:-}"

if ! command -v pm2 >/dev/null 2>&1; then
  echo "未找到 pm2,请先: npm install -g pm2" >&2
  exit 1
fi

cd "${HUB_DIR}"

case "${cmd}" in
  start)
    pm2 start "${ECO}"
    pm2 save 2>/dev/null || true
    ;;
  stop)
    pm2 stop manual-agent-binance manual-agent-okx manual-agent-gate 2>/dev/null || true
    ;;
  restart)
    pm2 restart manual-agent-binance manual-agent-okx manual-agent-gate 2>/dev/null \
      || pm2 start "${ECO}"
    ;;
  status)
    pm2 status
    ;;
  logs)
    pm2 logs manual-agent-binance manual-agent-okx manual-agent-gate --lines 100
    ;;
  delete)
    pm2 delete manual-agent-binance manual-agent-okx manual-agent-gate 2>/dev/null || true
    ;;
  *)
    usage
    exit 1
    ;;
esac
