#!/usr/bin/env bash
# deploy/lib/uninstall.sh — 一键卸载指定槽位（仅该槽位 PM2 + 目录）
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"

main_uninstall() {
  require_root

  resolve_slot "${INSTANCE_SLOT:-1}"

  local root=""
  if ! root="$(resolve_repo_root)"; then
    if [[ -d "${INSTALL_ROOT}" ]]; then
      root="${INSTALL_ROOT}"
    else
      die "未找到安装目录 ${INSTALL_ROOT}"
    fi
  fi
  REPO_ROOT="${root}"
  INSTALL_ROOT="${root}"
  apply_slot_for_root "${root}"

  echo ""
  echo "将卸载 比特骆驼自动化对冲系统 槽位 ${INSTANCE_SLOT}:"
  echo "  - 停止并删除 PM2 进程: ${PM2_APP_NAME}"
  echo "  - 删除安装目录: ${INSTALL_ROOT}"
  echo "  - 备份 .env / 数据库到 ${BACKUP_ROOT}"
  echo "  - 不影响其它槽位 / 其它 PM2 / 系统 Python、Node、PM2"
  echo ""
  if ! confirm_yes "确认卸载并删除 ${INSTALL_ROOT}?"; then
    log "已取消卸载"
    return 0
  fi

  local stamp backup_dir
  stamp="$(TZ="${TZ_NAME}" date +%Y%m%d-%H%M%S)"
  backup_dir="${BACKUP_ROOT}/pre-uninstall-slot${INSTANCE_SLOT}-${stamp}"
  mkdir -p "${backup_dir}"

  step "备份配置与数据"
  if [[ -f "${REPO_ROOT}/.env" ]]; then
    cp -a "${REPO_ROOT}/.env" "${backup_dir}/.env"
  fi
  if [[ -d "${REPO_ROOT}/backend/data" ]]; then
    cp -a "${REPO_ROOT}/backend/data" "${backup_dir}/data" 2>/dev/null || true
  fi
  {
    echo "created_at=${stamp}"
    echo "instance_slot=${INSTANCE_SLOT}"
    echo "install_root=${INSTALL_ROOT}"
    echo "api_port=${API_PORT}"
    echo "pm2_app=${PM2_APP_NAME}"
    echo "action=rm_rf_install_root"
  } >"${backup_dir}/uninstall.manifest"

  step "停止并移除 PM2 进程 ${PM2_APP_NAME}"
  pm2_stop_project
  pm2_delete_project

  step "删除安装目录 ${INSTALL_ROOT}"
  if [[ -d "${INSTALL_ROOT}" ]]; then
    if is_allowed_install_root "${INSTALL_ROOT}"; then
      rm -rf "${INSTALL_ROOT}"
      log "已删除: ${INSTALL_ROOT}"
    elif [[ "${ALLOW_UNSAFE_UNINSTALL:-}" == "1" ]]; then
      rm -rf "${INSTALL_ROOT}"
      log "已删除(ALLOW_UNSAFE_UNINSTALL=1): ${INSTALL_ROOT}"
    else
      die "拒绝删除非约定路径 ${INSTALL_ROOT}；允许: /opt/eth_hedge_sim[_2|_3]；或 ALLOW_UNSAFE_UNINSTALL=1"
    fi
  else
    log "安装目录不存在,跳过删除"
  fi

  # 清理历史「移走未删」残留（仅当前槽位前缀）
  local leftover base
  base="${INSTALL_ROOT}"
  for leftover in "${base}.removed."* "${base}.old."*; do
    if [[ -e "${leftover}" ]]; then
      rm -rf "${leftover}"
      log "已清理残留: ${leftover}"
    fi
  done

  echo ""
  echo "卸载完成."
  echo "  槽位: ${INSTANCE_SLOT}"
  echo "  配置/数据备份: ${backup_dir}"
  echo "  安装目录已删除: ${INSTALL_ROOT}"
  echo ""
  echo "重新部署该槽位:"
  echo "  bash /opt/eth_hedge_sim/deploy/manage.sh   # 选 1 → 槽位 ${INSTANCE_SLOT}"
  echo "  或: INSTANCE_SLOT=${INSTANCE_SLOT} SKIP_SLOT_PROMPT=1 bash …/deploy/lib/install.sh"
}

main_uninstall "$@"
