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

# ============================================
# Xray 卸载脚本
# 停止服务 → 备份 → 清理配置/防火墙/调优
# ============================================

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

log()   { echo -e "${GREEN}[INFO]${NC} $*"; }
warn()  { echo -e "${YELLOW}[WARN]${NC} $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }

# ===== 检查 root =====
if [ "$(id -u)" -ne 0 ]; then
    error "请使用 root 用户运行: sudo bash uninstall.sh"
    exit 1
fi

# ===== 加载配置 =====
if [ -f .env ]; then
    sed -i 's/\r$//' .env
    set -a; source .env; set +a
fi

XRAY_PORT="${XRAY_PORT:-443}"
BACKUP_DIR="${BACKUP_DIR:-/var/backups/xray}"

# ===== 确认操作 =====
echo ""
echo -e "${RED}╔══════════════════════════════════════════════════╗${NC}"
echo -e "${RED}║           ⚠  即将卸载 Xray 及所有配置  ⚠         ║${NC}"
echo -e "${RED}╚══════════════════════════════════════════════════╝${NC}"
echo ""
echo "将执行以下操作："
echo "  1. 停止并禁用 Xray 服务"
echo "  2. 卸载 Xray 程序"
echo "  3. 删除 Xray 配置文件"
echo "  4. 移除网络调优配置"
echo "  5. 关闭防火墙端口 ${XRAY_PORT}"
echo ""
echo "涉及的目录："
echo "  配置目录: /usr/local/etc/xray/"
echo "  备份目录: ${BACKUP_DIR}（保留）"
echo "  部署目录: ${SCRIPT_DIR}"
echo ""
echo -e "${YELLOW}备份目录将保留，不会被删除。${NC}"
echo ""
read -r -p "确定要继续卸载吗？输入 YES 确认: " confirm
if [ "$confirm" != "YES" ]; then
    log "已取消卸载"
    exit 0
fi

# ===== 卸载前备份 =====
echo ""
read -r -p "是否在卸载前执行一次备份？(y/N): " do_backup
if [[ "$do_backup" =~ ^[Yy]$ ]]; then
    if [ -f backup.sh ]; then
        log "正在执行备份..."
        bash backup.sh
        log "备份完成"
    else
        warn "backup.sh 不存在，跳过备份"
    fi
fi

# ===== 1. 停止并禁用 Xray 服务 =====
echo ""
log "正在停止 Xray 服务..."
if systemctl is-active --quiet xray 2>/dev/null; then
    systemctl stop xray
    log "Xray 服务已停止"
else
    log "Xray 服务未运行"
fi
systemctl disable xray 2>/dev/null || true

# ===== 2. 卸载 Xray =====
log "正在卸载 Xray..."
if [ -f /usr/local/bin/xray ]; then
    # 使用官方卸载方式
    bash <(curl -fsSL https://raw.githubusercontent.com/XTLS/Xray-install/main/install-release.sh) --remove 2>/dev/null || true
    # 手动清理残留
    rm -f /usr/local/bin/xray
    rm -rf /usr/local/etc/xray
    rm -rf /usr/local/share/xray
    rm -f /etc/systemd/system/xray.service
    rm -f /etc/systemd/system/xray@.service
    systemctl daemon-reload
    log "Xray 已卸载"
else
    log "Xray 未安装，跳过"
fi

# ===== 3. 移除网络调优配置 =====
log "正在移除网络调优配置..."
if [ -f /etc/sysctl.d/99-xray-turbo.conf ]; then
    rm -f /etc/sysctl.d/99-xray-turbo.conf
    sysctl --system > /dev/null 2>&1
    log "网络调优配置已移除"
else
    log "网络调优配置不存在，跳过"
fi

# ===== 4. 关闭防火墙端口 =====
log "正在关闭防火墙端口 ${XRAY_PORT}..."
if command -v ufw &>/dev/null; then
    ufw delete allow "${XRAY_PORT}/tcp" 2>/dev/null || true
    ufw reload 2>/dev/null || true
    log "ufw 已关闭端口 ${XRAY_PORT}/tcp"
elif command -v firewall-cmd &>/dev/null; then
    firewall-cmd --permanent --remove-port="${XRAY_PORT}/tcp" 2>/dev/null || true
    firewall-cmd --reload 2>/dev/null || true
    log "firewalld 已关闭端口 ${XRAY_PORT}/tcp"
else
    warn "未检测到防火墙工具，请手动关闭端口 ${XRAY_PORT}/tcp"
fi

# ===== 5. 删除部署目录 =====
echo ""
read -r -p "是否删除部署目录 ${SCRIPT_DIR}？(y/N): " del_deploy
if [[ "$del_deploy" =~ ^[Yy]$ ]]; then
    cd /opt
    rm -rf "$SCRIPT_DIR"
    log "已删除部署目录"
else
    warn "保留部署目录: ${SCRIPT_DIR}"
fi

# ===== 完成 =====
echo ""
log "Xray 卸载完成"
echo ""
echo "保留的内容："
echo "  备份目录: ${BACKUP_DIR}"
[[ ! "$del_deploy" =~ ^[Yy]$ ]] && echo "  部署目录: ${SCRIPT_DIR}"
echo ""
echo "如需恢复，请参考 README.md 中的「恢复备份」章节。"
