#!/usr/bin/env bash
# deploy/lib/uninstall.sh — 一键卸载
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}"

  if ! confirm_uninstall; then
    log "已取消卸载"
    return 0
  fi

  local stamp backup_dir removed_dir
  stamp="$(TZ="${TZ_NAME}" date +%Y%m%d-%H%M%S)"
  backup_dir="${BACKUP_ROOT}/pre-uninstall-${stamp}"
  removed_dir="${INSTALL_ROOT}.removed.${stamp}"

  step "备份配置到 ${backup_dir}"
  backup_configs_to "${REPO_ROOT}" "${backup_dir}"
  {
    echo "created_at=${stamp}"
    echo "install_root=${INSTALL_ROOT}"
    echo "removed_dir=${removed_dir}"
  } >"${backup_dir}/uninstall.manifest"

  step "停止并移除本项目 PM2 进程(不影响其它 PM2)"
  pm2_stop_project_apps
  pm2_delete_project_apps

  remove_backup_cron_all

  step "移走安装目录"
  if [[ -d "${INSTALL_ROOT}" ]]; then
    mv "${INSTALL_ROOT}" "${removed_dir}"
    log "已移动: ${INSTALL_ROOT} -> ${removed_dir}"
  else
    log "安装目录不存在,跳过"
  fi

  echo ""
  echo "卸载完成."
  echo "  配置备份: ${backup_dir}"
  echo "  旧目录:   ${removed_dir} (确认无误后可手动删除)"
  echo ""
  echo "回滚示例:"
  echo "  mv ${removed_dir} ${INSTALL_ROOT}"
  echo "  bash ${INSTALL_ROOT}/deploy/manage.sh  # 选 1 修复环境"
}

main_uninstall "$@"
