#!/usr/bin/env bash
set -Eeuo pipefail

REMOVE_DDNS=0
REMOVE_NYA=0
REMOVE_IP_ROTATE=0
REMOVE_CADU=0
REMOVE_NEZHA=0
ASSUME_YES=0
BOOTSTRAP_STATE_DIR="${BOOTSTRAP_STATE_DIR:-/var/lib/cadu-bootstrap}"

usage() {
  cat <<'USAGE'
用法：uninstall.sh [卸载项目] [--yes]

卸载项目：
  1              卸载 DDNS
  2              卸载 NyanPass
  3              卸载 aws.sb 自动换 IP
  4              卸载 CADU
  5              卸载全部组件
  6              卸载哪吒 Agent
  --all          卸载 DDNS、NyanPass、自动换 IP、CADU 和哪吒 Agent
  --ddns         卸载 DDNS 服务及其凭据和数据
  --nya          卸载已记录的随机名称 NyanPass 服务及其文件
  --ip-rotate    卸载 aws.sb 自动换 IP 服务及其数据
  --cadu         调用 CADU 自带的完整卸载功能
  --nezha        卸载哪吒 Agent 服务及其文件

选项：
  --yes          跳过确认提示（用于自动化）
  -h, --help     显示帮助

在终端中不带卸载项目运行时，将显示数字选择菜单。
USAGE
}

die() {
  printf '错误：%s\n' "$*" >&2
  exit 1
}

if [ "$#" -eq 0 ] && [ -t 0 ]; then
  usage
  printf '\n请输入一个或多个数字，多个数字用空格分隔：'
  read -r -a menu_choices
  set -- "${menu_choices[@]}"
fi

while [ "$#" -gt 0 ]; do
  case "$1" in
    5|--all)
      REMOVE_DDNS=1
      REMOVE_NYA=1
      REMOVE_IP_ROTATE=1
      REMOVE_CADU=1
      REMOVE_NEZHA=1
      shift
      ;;
    1|--ddns) REMOVE_DDNS=1; shift ;;
    2|--nya) REMOVE_NYA=1; shift ;;
    3|--ip-rotate) REMOVE_IP_ROTATE=1; shift ;;
    4|--cadu) REMOVE_CADU=1; shift ;;
    6|--nezha) REMOVE_NEZHA=1; shift ;;
    --yes) ASSUME_YES=1; shift ;;
    -h|--help) usage; exit 0 ;;
    *) die "未知选项：$1" ;;
  esac
done

[ "$(id -u)" -eq 0 ] || die "卸载脚本必须以 root 身份运行"
if [ "$REMOVE_DDNS" -eq 0 ] && [ "$REMOVE_NYA" -eq 0 ] && \
   [ "$REMOVE_IP_ROTATE" -eq 0 ] && [ "$REMOVE_CADU" -eq 0 ] && \
   [ "$REMOVE_NEZHA" -eq 0 ]; then
  usage >&2
  die "请至少选择一个卸载项目，或使用 --all"
fi

printf '%s\n' '========== CADU 统一卸载计划 =========='
[ "$REMOVE_IP_ROTATE" -eq 1 ] && printf '%s\n' '- aws.sb 自动换 IP'
[ "$REMOVE_NYA" -eq 1 ] && printf '%s\n' '- NyanPass 节点客户端'
[ "$REMOVE_DDNS" -eq 1 ] && printf '%s\n' '- DDNS 服务、凭据和数据'
[ "$REMOVE_CADU" -eq 1 ] && printf '%s\n' '- CADU、定时体检、SSH 基线和托管配置'
[ "$REMOVE_NEZHA" -eq 1 ] && printf '%s\n' '- 哪吒 Agent'

if [ "$ASSUME_YES" -ne 1 ]; then
  [ -t 0 ] || die "确认操作需要终端；无人值守执行请添加 --yes"
  read -r -p '输入 YES 确认卸载：' answer
  [ "$answer" = "YES" ] || die "已取消卸载"
fi

stop_and_remove_service() {
  local service="$1"
  systemctl disable --now "$service" >/dev/null 2>&1 || true
  rm -f "/etc/systemd/system/$service"
}

if [ "$REMOVE_IP_ROTATE" -eq 1 ]; then
  printf '正在卸载 aws.sb 自动换 IP...\n'
  stop_and_remove_service cadu-ip-rotate.service
  rm -f /usr/local/libexec/cadu-ip-rotate-agent.py /usr/local/bin/cadu-ip-rotate
  rm -rf /etc/cadu-ip-rotate
fi

if [ "$REMOVE_NEZHA" -eq 1 ]; then
  printf '正在卸载哪吒 Agent...\n'
  if [ -x /opt/nezha/agent/nezha-agent ]; then
    while IFS= read -r config; do
      /opt/nezha/agent/nezha-agent service -c "$config" uninstall >/dev/null 2>&1 || true
    done < <(find /opt/nezha/agent -maxdepth 1 -type f -name '*config*.yml' -print)
  fi
  stop_and_remove_service nezha-agent.service
  rm -rf /opt/nezha
fi

if [ "$REMOVE_NYA" -eq 1 ]; then
  printf '正在卸载 NyanPass...\n'
  nya_name_file="${BOOTSTRAP_STATE_DIR}/nyanpass-service-name"
  nya_name=""
  if [ -s "$nya_name_file" ]; then
    nya_name="$(tr -d '[:space:]' <"$nya_name_file")"
  fi
  if [[ -n "$nya_name" && "$nya_name" =~ ^[A-Za-z0-9_-]+$ ]]; then
    stop_and_remove_service "${nya_name}.service"
    rm -rf "/opt/${nya_name}"
    printf '已卸载 NyanPass 服务：%s\n' "$nya_name"
  else
    printf '未找到有效的 NyanPass 服务名，为避免误删，未处理未知服务。\n'
  fi
  rm -f "$nya_name_file"

  if [ -f "${BOOTSTRAP_STATE_DIR}/nya-dns-installed" ]; then
    printf '正在恢复 NyanPass 安装前的 DNS 配置...\n'
    chattr -i /etc/resolv.conf 2>/dev/null || true
    rm -f /etc/resolv.conf /etc/dnsmasq.d/cadu-nya.conf
    if [ -e "${BOOTSTRAP_STATE_DIR}/resolv.conf.original" ] ||
       [ -L "${BOOTSTRAP_STATE_DIR}/resolv.conf.original" ]; then
      cp -a "${BOOTSTRAP_STATE_DIR}/resolv.conf.original" /etc/resolv.conf
    fi
    if [ -f "${BOOTSTRAP_STATE_DIR}/dnsmasq-preexisting" ]; then
      if [ -f "${BOOTSTRAP_STATE_DIR}/dnsmasq-was-active" ]; then
        systemctl restart dnsmasq.service >/dev/null 2>&1 || true
      else
        systemctl stop dnsmasq.service >/dev/null 2>&1 || true
      fi
    else
      systemctl disable --now dnsmasq.service >/dev/null 2>&1 || true
    fi
    rm -f "${BOOTSTRAP_STATE_DIR}/nya-dns-installed" \
      "${BOOTSTRAP_STATE_DIR}/resolv.conf.original" \
      "${BOOTSTRAP_STATE_DIR}/dnsmasq-preexisting" \
      "${BOOTSTRAP_STATE_DIR}/dnsmasq-was-active"
  fi
fi

if [ "$REMOVE_DDNS" -eq 1 ]; then
  printf '正在卸载 DDNS...\n'
  stop_and_remove_service cadu-ddns.service
  rm -f /usr/local/libexec/cadu-ddns-agent.py /usr/local/bin/cadu-ddns
  rm -rf /etc/cadu-ddns
fi

systemctl daemon-reload
systemctl reset-failed >/dev/null 2>&1 || true

if [ "$REMOVE_CADU" -eq 1 ]; then
  printf '正在卸载 CADU...\n'
  if command -v cadu >/dev/null 2>&1; then
    cadu --uninstall --yes
  else
    printf '未安装 CADU 命令，已跳过。\n'
  fi
fi

if [ "$REMOVE_DDNS" -eq 1 ] && [ "$REMOVE_NYA" -eq 1 ] && \
   [ "$REMOVE_IP_ROTATE" -eq 1 ] && [ "$REMOVE_CADU" -eq 1 ] && \
   [ "$REMOVE_NEZHA" -eq 1 ]; then
  rm -rf "$BOOTSTRAP_STATE_DIR"
else
  rm -f "${BOOTSTRAP_STATE_DIR}/completed"
fi

printf '%s\n' '统一卸载已完成。'
