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

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

_COMMON="$ROOT/deploy/lib/common.sh"
if [[ -f "$_COMMON" ]]; then
  # shellcheck source=lib/common.sh
  source "$_COMMON"
  apply_slot_for_root "$ROOT"
fi

# 有 root 时：检测 Python / Node / PM2，缺则装、有则跳过（pull 前用当前脚本）
if [[ -f "$_COMMON" ]] && [[ "$(id -u)" -eq 0 ]]; then
  ensure_system_deps
fi

echo "[比特骆驼] pull @ $ROOT (slot=${INSTANCE_SLOT:-?} port=${API_PORT:-?})"
if [[ -d "$ROOT/.git" ]]; then
  git fetch --all --prune
  git pull --ff-only
fi

# pull 后再检测一次，确保用上仓库里最新的 python3-venv / ensurepip 逻辑
if [[ -f "$_COMMON" ]]; then
  # shellcheck source=lib/common.sh
  source "$_COMMON"
  apply_slot_for_root "$ROOT"
fi
if [[ -f "$_COMMON" ]] && [[ "$(id -u)" -eq 0 ]]; then
  ensure_system_deps
fi

if [[ ! -f "$ROOT/.env" ]]; then
  echo "[比特骆驼] missing .env — copy from example"
  cp "$ROOT/.env.example" "$ROOT/.env"
  # 云上测试机默认直连 OKX；端口按槽位
  local_port="${API_PORT:-5155}"
  sed -i 's/^OKX_HTTP_PROXY=.*/OKX_HTTP_PROXY=/' "$ROOT/.env" || true
  sed -i "s/^API_PORT=.*/API_PORT=${local_port}/" "$ROOT/.env" || true
  sed -i 's/^ENV_NAME=.*/ENV_NAME=test/' "$ROOT/.env" || true
  sed -i 's/^EXCHANGE=.*/EXCHANGE=okx/' "$ROOT/.env" || true
  if [[ -f "$_COMMON" ]]; then
    secret="$(random_auth_secret)"
    if [[ -n "${secret}" ]]; then
      sed -i "s/^AUTH_SECRET=.*/AUTH_SECRET=${secret}/" "$ROOT/.env" || true
    fi
  fi
  echo "[比特骆驼] wrote .env — API_PORT=${local_port}；请按需修改 AUTH_*"
fi

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

# 缺 ensurepip 时会留下半截 .venv：常有 bin/python3 却没有 activate，不能只看目录是否存在
project_venv_ok() {
  [[ -f "$ROOT/.venv/bin/activate" ]] \
    && [[ -x "$ROOT/.venv/bin/python3" ]] \
    && "$ROOT/.venv/bin/python3" -c "import sys" >/dev/null 2>&1
}

if ! project_venv_ok; then
  if [[ -e "$ROOT/.venv" ]]; then
    echo "[比特骆驼] .venv 不可用（半截/损坏），删除后重建"
    rm -rf "$ROOT/.venv"
  fi
  echo "[比特骆驼] create venv"
  if ! python3 -m venv "$ROOT/.venv"; then
    pyver="$(python3 -c 'import sys; print("%d.%d" % sys.version_info[:2])' 2>/dev/null || echo "3")"
    echo "ERROR: 创建 venv 失败（多为缺 python3-venv / ensurepip）。" >&2
    echo "  可执行: apt install -y python3-venv python${pyver}-venv" >&2
    rm -rf "$ROOT/.venv"
    exit 1
  fi
  if ! project_venv_ok; then
    echo "ERROR: venv 创建后仍不可用（缺 activate 或 python）。" >&2
    rm -rf "$ROOT/.venv"
    exit 1
  fi
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

# 按本目录槽位重写 PM2 配置（避免 git pull 盖回槽位 1 硬编码）
if [[ -f "$_COMMON" ]]; then
  write_ecosystem_config "$ROOT" "${PM2_APP_NAME}" "${API_PORT}"
fi

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

echo "[比特骆驼] done. slot=${INSTANCE_SLOT:-1} health: http://127.0.0.1:${API_PORT:-5155}/health"
