#!/usr/bin/env bash
# 一键更新/部署：仅 git pull，禁止 scp 传代码。
# 用法:
#   bash /opt/eth_hedge_sim/deploy/pull_and_restart.sh
#   或通过 manage.sh 选 1/3
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"

# 有 root 时：检测 Python / Node / PM2，缺则装、有则跳过
if [[ -f "$ROOT/deploy/lib/common.sh" ]] && [[ "$(id -u)" -eq 0 ]]; then
  # shellcheck source=lib/common.sh
  source "$ROOT/deploy/lib/common.sh"
  ensure_system_deps
fi

echo "[比特骆驼] pull @ $ROOT"
if [[ -d "$ROOT/.git" ]]; then
  git fetch --all --prune
  git pull --ff-only
fi

if [[ ! -f "$ROOT/.env" ]]; then
  echo "[比特骆驼] missing .env — copy from example"
  cp "$ROOT/.env.example" "$ROOT/.env"
  # 云上测试机默认直连 OKX
  sed -i 's/^OKX_HTTP_PROXY=.*/OKX_HTTP_PROXY=/' "$ROOT/.env" || true
  sed -i 's/^API_PORT=.*/API_PORT=5155/' "$ROOT/.env" || true
  sed -i 's/^ENV_NAME=.*/ENV_NAME=test/' "$ROOT/.env" || true
  sed -i 's/^EXCHANGE=.*/EXCHANGE=okx/' "$ROOT/.env" || true
  echo "[比特骆驼] wrote .env — please review AUTH_* secrets"
fi

if ! command -v python3 >/dev/null 2>&1; then
  echo "ERROR: python3 not found. 请用 manage.sh 一键部署自动安装。"
  exit 1
fi

if [[ ! -d "$ROOT/.venv" ]]; then
  echo "[比特骆驼] create venv"
  python3 -m venv "$ROOT/.venv"
fi
# shellcheck disable=SC1091
source "$ROOT/.venv/bin/activate"
pip install -U pip
pip install -r "$ROOT/requirements.txt"

if ! command -v npm >/dev/null 2>&1; then
  echo "ERROR: npm not found. Install Node.js 18+ first (manage.sh 一键部署会自动装)."
  exit 1
fi

(
  cd "$ROOT/frontend"
  if [[ -f package-lock.json ]]; then npm ci; else npm install; fi
  npm run build
)

if ! command -v pm2 >/dev/null 2>&1; then
  echo "[比特骆驼] install pm2"
  npm install -g pm2
else
  echo "[比特骆驼] pm2 already present, skip install"
fi

# 仅 reload 本项目进程，禁止 pm2 restart all
pm2 startOrReload "$ROOT/deploy/ecosystem.config.cjs" --update-env
pm2 save

echo "[比特骆驼] done. health: http://127.0.0.1:5155/health"
