#!/usr/bin/env bash
# deploy/lib/install.sh — 一键部署策略机（支持槽位 1/2/3）
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"

run_pipeline() {
  local root="$1"
  REPO_ROOT="${root}"
  INSTALL_ROOT="${root}"
  apply_slot_for_root "${root}"
  step "构建并启动策略机 (pull_and_restart.sh) slot=${INSTANCE_SLOT}"
  bash "${REPO_ROOT}/deploy/pull_and_restart.sh"
  pm2_save_startup
  verify_health "${API_PORT}" || true
  print_post_install_guide
}

install_fresh() {
  require_root
  step "一键部署策略机 — 环境检测与依赖"
  ensure_system_deps
  assert_port_free_for_install "${API_PORT}" "${PM2_APP_NAME}"
  step "克隆仓库 → ${INSTALL_ROOT}（槽位 ${INSTANCE_SLOT} / :${API_PORT}）"
  if [[ -d "${INSTALL_ROOT}" ]]; then
    die "目录已存在: ${INSTALL_ROOT}，请先卸载或选修复"
  fi
  mkdir -p "$(dirname "${INSTALL_ROOT}")"
  git clone -b "${GIT_BRANCH}" "${GIT_URL}" "${INSTALL_ROOT}"
  run_pipeline "${INSTALL_ROOT}"
}

install_repair() {
  require_root
  step "修复部署 — 环境检测与依赖"
  ensure_system_deps
  if ! REPO_ROOT="$(resolve_repo_root)"; then
    die "未找到安装目录 ${INSTALL_ROOT}"
  fi
  step "修复环境(保留 .env 与数据库) slot=${INSTANCE_SLOT}"
  run_pipeline "${REPO_ROOT}"
}

handle_existing() {
  echo ""
  echo "检测到已部署: ${INSTALL_ROOT}（槽位 ${INSTANCE_SLOT}）"
  echo "  a) 取消"
  echo "  b) 修复/重装环境(保留 .env 与 SQLite)"
  local choice=""
  cm_read choice "请选择 [a/b]: "
  case "${choice}" in
    b|B) install_repair ;;
    *) log "已取消" ;;
  esac
}

main_install() {
  require_root
  # manage.sh 已 prompt；直接调用时按 INSTANCE_SLOT / INSTALL_ROOT 对齐
  if [[ "${INSTALL_ROOT}" == "/opt/eth_hedge_sim_2" ]]; then
    resolve_slot 2
  elif [[ "${INSTALL_ROOT}" == "/opt/eth_hedge_sim_3" ]]; then
    resolve_slot 3
  else
    resolve_slot "${INSTANCE_SLOT:-1}"
  fi

  if repo_ready "${INSTALL_ROOT}"; then
    handle_existing
  else
    install_fresh
  fi
}

main_install "$@"
