#!/usr/bin/env bash
# deploy/lib/uninstall.sh — 一键卸载（仅本项目 PM2，删除 /opt 安装目录）
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

  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}"

  echo ""
  echo "将卸载 比特骆驼自动化对冲系统 (eth_hedge_sim):"
  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-${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 "install_root=${INSTALL_ROOT}"
    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
    # 安全：只允许删除约定安装路径（默认 /opt/eth_hedge_sim）
    case "${INSTALL_ROOT}" in
      /opt/eth_hedge_sim|/opt/eth_hedge_sim/)
        rm -rf "${INSTALL_ROOT}"
        log "已删除: ${INSTALL_ROOT}"
        ;;
      *)
        if [[ "${ALLOW_UNSAFE_UNINSTALL:-}" == "1" ]]; then
          rm -rf "${INSTALL_ROOT}"
          log "已删除(ALLOW_UNSAFE_UNINSTALL=1): ${INSTALL_ROOT}"
        else
          die "拒绝删除非默认路径 ${INSTALL_ROOT}；若确认，设置 ALLOW_UNSAFE_UNINSTALL=1"
        fi
        ;;
    esac
  else
    log "安装目录不存在,跳过删除"
  fi

  # 清理历史「移走未删」残留
  local leftover
  for leftover in /opt/eth_hedge_sim.removed.* /opt/eth_hedge_sim.old.*; do
    if [[ -e "${leftover}" ]]; then
      rm -rf "${leftover}"
      log "已清理残留: ${leftover}"
    fi
  done

  echo ""
  echo "卸载完成."
  echo "  配置/数据备份: ${backup_dir}"
  echo "  安装目录已删除: ${INSTALL_ROOT}"
  echo ""
  echo "重新部署:"
  echo "  curl -fsSL https://git.bz121.com/dekun/eth_hedge_sim/raw/branch/main/deploy/manage.sh | bash"
}

main_uninstall "$@"
