#!/bin/bash

# 输出开始信息
echo "开始卸载阿里云云盾相关进程与文件..."

# 强制终止所有相关的阿里云云盾进程
for service in aliyun-service CmsGoAgent.linux-amd64 AliYunDun AliYunDunUpdate AliSecGuard AliSecureCheck assist_daemon; do
    if pgrep -f "$service" > /dev/null; then
        killall -9 "$service"
        echo "已终止进程: $service"
    else
        echo "未找到进程: $service"
    fi
done

# 删除残余文件和服务
echo "删除阿里云云盾相关的残留文件..."
rm_paths=(
    "/etc/rc2.d/S80aegis" "/etc/rc3.d/S80aegis" "/etc/rc4.d/S80aegis" "/etc/rc5.d/S80aegis" 
    "/etc/rc.d/rc2.d/S80aegis" "/etc/rc.d/rc3.d/S80aegis" "/etc/rc.d/rc4.d/S80aegis" 
    "/etc/rc.d/rc5.d/S80aegis" "/etc/init.d/aegis" "/etc/init.d/agentwatch" 
    "/usr/sbin/aliyun-service" "/usr/sbin/aliyun_installer" "/usr/sbin/aliyun-service.backup" 
    "/usr/local/aegis" "/usr/local/cloudmonitor" "/usr/local/share/aliyun-assist" 
    "/usr/local/share/assist-daemon" "/usr/sbin/aliyun-service"
)

for path in "${rm_paths[@]}"; do
    if [ -e "$path" ]; then
        rm -rf "$path"
        echo "已删除: $path"
    else
        echo "文件不存在: $path"
    fi
done

# 下载并执行卸载脚本
echo "执行阿里云云盾官方卸载脚本..."
wget -q http://update.aegis.aliyun.com/download/uninstall.sh
chmod +x uninstall.sh
./uninstall.sh && echo "uninstall.sh 执行完毕。"

wget -q http://update.aegis.aliyun.com/download/quartz_uninstall.sh
chmod +x quartz_uninstall.sh
./quartz_uninstall.sh && echo "quartz_uninstall.sh 执行完毕。"

# 检测是否有iptables或ufw，并根据系统使用适合的工具
if command -v ufw >/dev/null 2>&1; then
    echo "检测到系统使用 ufw，开始使用 ufw 屏蔽阿里云云盾相关 IP..."
    ufw enable
    iptables_rules=(
        "140.205.201.0/28" "140.205.201.16/29" "140.205.201.32/28" 
        "140.205.225.192/29" "140.205.225.200/30" "140.205.225.184/29" 
        "140.205.225.183/32" "140.205.225.206/32" "140.205.225.205/32" 
        "140.205.225.195/32" "140.205.225.204/32"
    )

    for ip in "${iptables_rules[@]}"; do
        if ! ufw status | grep "$ip" > /dev/null; then
            ufw deny from "$ip"
            echo "已通过 ufw 屏蔽 IP: $ip"
        else
            echo "IP 已通过 ufw 屏蔽: $ip"
        fi
    done
elif command -v iptables >/dev/null 2>&1; then
    echo "检测到系统使用 iptables，开始使用 iptables 屏蔽阿里云云盾相关 IP..."
    iptables_rules=(
        "140.205.201.0/28" "140.205.201.16/29" "140.205.201.32/28" 
        "140.205.225.192/29" "140.205.225.200/30" "140.205.225.184/29" 
        "140.205.225.183/32" "140.205.225.206/32" "140.205.225.205/32" 
        "140.205.225.195/32" "140.205.225.204/32"
    )

    for ip in "${iptables_rules[@]}"; do
        if ! iptables -C INPUT -s "$ip" -j DROP &>/dev/null; then
            iptables -I INPUT -s "$ip" -j DROP
            echo "已通过 iptables 屏蔽 IP: $ip"
        else
            echo "IP 已通过 iptables 屏蔽: $ip"
        fi
    done
else
    echo "系统未检测到 ufw 或 iptables，无法屏蔽 IP，请手动检查防火墙设置。"
fi

# 检查是否有阿里云云盾相关进程仍在运行
echo "检查是否还有阿里云云盾相关的进程..."
if ps -aux | grep -E 'aliyun|AliYunDun' | grep -v grep; then
    echo "警告：仍然存在阿里云云盾相关进程，请手动检查！"
else
    echo "没有检测到阿里云云盾相关进程，卸载成功。"
fi

# 输出完成信息
echo "阿里云云盾卸载与清理完成。"
