#!/usr/bin/env bash
# 封 BT 滥用的一键脚本（nftables）

set -e

echo "==== nftables 封 BT 脚本开始 ===="

if [ "$(id -u)" -ne 0 ]; then
    echo "请用 root 用户运行本脚本"
    exit 1
fi

install_nftables() {
    if command -v nft >/dev/null 2>&1; then
        echo "nft 已存在"
        return
    fi

    echo "安装 nftables..."
    if command -v apt-get >/dev/null 2>&1; then
        apt-get update -y
        apt-get install -y nftables
    elif command -v yum >/dev/null 2>&1; then
        yum install -y nftables
    elif command -v dnf >/dev/null 2>&1; then
        dnf install -y nftables
    fi
}

install_nftables

# 创建表
nft list table inet filter >/dev/null 2>&1 || nft add table inet filter

# 创建链
for c in input output forward; do
    if ! nft list chain inet filter $c >/dev/null 2>&1; then
        nft add chain inet filter $c "{ type filter hook $c priority 0; policy accept; }"
    fi
done

# 添加 BT 端口封禁规则
add_rule() {
    chain=$1
    proto=$2
    port=$3

    if ! nft list chain inet filter $chain | grep -q "$proto dport $port"; then
        nft add rule inet filter $chain $proto dport $port drop
    fi
}

for chain in input output forward; do
    add_rule $chain tcp "6881-6999"
    add_rule $chain udp "6881-6999"
    add_rule $chain tcp 6969
    add_rule $chain udp 6969
    add_rule $chain tcp 51413
    add_rule $chain udp 51413
done

# 保存
nft list ruleset > /etc/nftables.conf
systemctl enable nftables >/dev/null 2>&1 || true
systemctl restart nftables >/dev/null 2>&1 || true

echo "==== 完成：已封 BT ===="
