#!/usr/bin/env bash
# 在服务器上检查中控是否为最新代码(无 api_trade_key,已装 multipart,进程可访问)
set -euo pipefail
HUB_DIR="$(cd "$(dirname "$0")/.." && pwd)"
cd "$HUB_DIR"

HUB_PORT=5100
if [[ -f .env ]]; then
  p=$(grep -E '^HUB_PORT=' .env 2>/dev/null | tail -1 | cut -d= -f2- | tr -d '\r" ')
  [[ -n "${p}" ]] && HUB_PORT="${p}"
fi
PING_URL="http://127.0.0.1:${HUB_PORT}/api/ping"

echo "=== hub.py 检查 ==="
if grep -n 'def api_trade_key' hub.py 2>/dev/null; then
  echo "FAIL: 仍是旧版 hub.py(含 api_trade_key),请 git pull"
  exit 1
fi
if ! grep -q 'HUB_BUILD' hub.py; then
  echo "FAIL: hub.py 缺少 HUB_BUILD 标记"
  exit 1
fi
echo "OK: 无 api_trade_key,含 HUB_BUILD"

echo "=== python-multipart ==="
# shellcheck source=/dev/null
source .venv/bin/activate
python -c "import multipart; print('OK:', multipart.__version__)"

echo "=== 端口 ${HUB_PORT} ==="
if command -v ss >/dev/null 2>&1; then
  ss -ltn | grep -E ":${HUB_PORT}\\b" || echo "WARN: 未监听 ${HUB_PORT},请 pm2 restart manual-trading-hub"
elif command -v netstat >/dev/null 2>&1; then
  netstat -ltn | grep -E ":${HUB_PORT}\\b" || echo "WARN: 未监听 ${HUB_PORT}"
else
  echo "(跳过端口检查)"
fi

echo "=== PM2 manual-trading-hub ==="
if command -v pm2 >/dev/null 2>&1; then
  pm2 describe manual-trading-hub 2>/dev/null | grep -E 'status|restarts|uptime|script path' || pm2 list | grep -i hub || true
fi

echo "=== GET ${PING_URL} ==="
HTTP_CODE=$(curl -sS -o /tmp/hub_ping_body.txt -w "%{http_code}" "${PING_URL}" || echo "000")
echo "HTTP ${HTTP_CODE}"
cat /tmp/hub_ping_body.txt
echo ""
if [[ "${HTTP_CODE}" == "200" ]]; then
  python -m json.tool /tmp/hub_ping_body.txt
  if grep -q '20260521-no-trade-ui' /tmp/hub_ping_body.txt; then
    echo "OK: build 正确"
  else
    echo "WARN: build 字段不是 20260521-no-trade-ui,请 pm2 restart manual-trading-hub"
  fi
else
  echo "FAIL: ping 未返回 200.常见原因:进程未启动或崩溃."
  echo "  执行: pm2 restart manual-trading-hub && sleep 2 && bash scripts/verify_hub_deploy.sh"
  exit 1
fi
