#!/bin/bash
# node-agent 节点一键卸载：停内核/agent 服务 → 删 systemd 单元、二进制、配置、数据、cron →
# 清 nginx 伪装站与契约反代 → 还原内核调优。与 setup-node.sh + deploy-agent.sh 的产物一一对应。
# 用法（在节点上，以 root 运行）：
#   curl -fsSL https://64.118.149.202.sslip.io/uninstall.sh | bash
#   或下载后：bash uninstall.sh
# 默认交互确认；ASSUME_YES=1 跳过确认（自动化用）。
# 说明：apt 依赖包（nginx/curl/socat/python3 等）不卸载，可能被其他服务共用；
#       nginx 本身保留，仅移除本方案的 decoy / agent-api 两个站点配置。
set -uo pipefail
log(){ echo "[$(date '+%H:%M:%S')] $1"; }

[ "$(id -u)" = "0" ] || { echo "ERROR: 请以 root 运行"; exit 1; }

if [ "${ASSUME_YES:-}" != "1" ]; then
  read -rp "确认卸载本节点的 node-agent/xray/hysteria 及全部配置数据？[y/N] " ANS </dev/tty
  case "$ANS" in y|Y|yes|YES) ;; *) echo "已取消"; exit 0;; esac
fi

# 先取 HY2 端口（删 ufw 规则用），随后 /etc/node-agent 会被整体删除
HY2_PORT=""
[ -f /etc/node-agent/node.env ] && HY2_PORT=$(grep -oP '^HY2_PORT=\K[0-9]+' /etc/node-agent/node.env || true)

# ── 停服务 + 删 systemd 单元 ──
log "stop & disable services"
systemctl disable --now node-agent xray hysteria >/dev/null 2>&1 || true
rm -f /etc/systemd/system/node-agent.service /etc/systemd/system/xray.service /etc/systemd/system/hysteria.service
systemctl daemon-reload

# ── 删二进制 / 配置 / 数据 ──
log "remove binaries, configs, data"
rm -f  /usr/local/bin/node-agent /usr/local/bin/xray /usr/local/bin/hysteria /usr/local/bin/node-host-update.sh
rm -rf /etc/node-agent /etc/hysteria /usr/local/etc/xray /usr/local/share/xray \
       /var/lib/node-agent /var/www/decoy

# ── host 自更新 cron + 日志 ──
rm -f /etc/cron.d/node-host-update /var/log/node-host-update.log

# ── acme.sh（卸载其 cron 续期任务并删目录）──
if [ -x ~/.acme.sh/acme.sh ]; then
  ~/.acme.sh/acme.sh --uninstall >/dev/null 2>&1 || true
fi
crontab -l 2>/dev/null | grep -v 'acme.sh' | crontab - 2>/dev/null || true
rm -rf ~/.acme.sh

# ── nginx：移除 decoy / agent-api 站点（setup 时删了 default 的 enabled 链接，顺手还原）──
log "cleanup nginx sites"
rm -f /etc/nginx/sites-available/decoy  /etc/nginx/sites-enabled/decoy \
      /etc/nginx/sites-available/agent-api /etc/nginx/sites-enabled/agent-api
[ -f /etc/nginx/sites-available/default ] && ln -sfn /etc/nginx/sites-available/default /etc/nginx/sites-enabled/default
if command -v nginx >/dev/null 2>&1 && systemctl is-active --quiet nginx; then
  nginx -t >/dev/null 2>&1 && systemctl reload nginx || log "WARN: nginx -t 失败，请人工检查"
fi

# ── 还原内核调优 ──
rm -f /etc/sysctl.d/99-node-agent.conf /etc/modules-load.d/bbr.conf
sysctl --system >/dev/null 2>&1 || true

# ── ufw 规则（best-effort）──
if command -v ufw >/dev/null 2>&1; then
  ufw delete allow 443/tcp  >/dev/null 2>&1 || true
  ufw delete allow 10443/tcp >/dev/null 2>&1 || true
  ufw delete allow 80/tcp   >/dev/null 2>&1 || true
  [ -n "$HY2_PORT" ] && ufw delete allow "${HY2_PORT}/udp" >/dev/null 2>&1 || true
fi

log "✓ 卸载完成"
echo "保留项：apt 包（nginx/curl/socat/python3/cron 等）与 nginx 本体。如需彻底清 nginx：apt-get purge -y nginx*"
