#!/usr/bin/env bash
# deploy/lib/update.sh — 更新（仅 git pull，禁止 scp）；支持单槽位或全部串行
set -e
set -u
if [ -n "${BASH_VERSION:-}" ]; then
  set -o pipefail
fi

LIB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=common.sh
source "${LIB_DIR}/common.sh"

update_one_slot() {
  local slot="$1"
  resolve_slot "${slot}"
  if ! repo_ready "${INSTALL_ROOT}"; then
    log "槽位 ${slot} 未安装（${INSTALL_ROOT}），跳过"
    return 0
  fi
  step "更新槽位 ${slot}: ${INSTALL_ROOT} :${API_PORT} ${PM2_APP_NAME}"
  ensure_system_deps
  bash "${INSTALL_ROOT}/deploy/pull_and_restart.sh"
  verify_health "${API_PORT}" || true
  log "槽位 ${slot} 更新完成"
}

update_all_slots() {
  local s
  local any=0
  step "串行更新全部已安装策略机槽位（避免同机并行 npm build）"
  for s in $(list_installed_slots); do
    any=1
    update_one_slot "${s}"
  done
  if [[ "${any}" -eq 0 ]]; then
    die "未找到已安装的策略机（槽位 1/2/3）"
  fi
  echo ""
  log "全部槽位更新完成"
}

main_update() {
  require_root
  local mode="${EHS_UPDATE_MODE:-one}"
  if [[ "${mode}" == "all" ]]; then
    update_all_slots
    return 0
  fi

  resolve_slot "${INSTANCE_SLOT:-1}"
  if ! REPO_ROOT="$(resolve_repo_root)"; then
    die "未找到安装目录 ${INSTALL_ROOT}，请先执行「1) 一键部署策略机」并选择该槽位"
  fi
  if ! repo_ready "${REPO_ROOT}"; then
    die "安装不完整: ${REPO_ROOT}"
  fi

  step "更新 — 环境检测 (缺则装，有则跳过)"
  ensure_system_deps
  step "更新槽位 ${INSTANCE_SLOT} (git pull + 构建 + pm2 reload)"
  bash "${REPO_ROOT}/deploy/pull_and_restart.sh"
  verify_health "${API_PORT}" || true
  echo ""
  log "更新完成 slot=${INSTANCE_SLOT} http://127.0.0.1:${API_PORT}/health"
}

main_update "$@"
