#!/bin/bash
set -e
#目标ip
DST_IP="172.31.253.74"
#出口ip
OUT_SRC_IP="172.31.253.73"
PORT_RANGE="10000-65535"

echo "🧱 正在配置永久转发..."
apt update -y && apt install -y nftables

cat > /etc/nftables.conf <<EOF
#!/usr/sbin/nft -f
flush ruleset

table inet filter {
    chain input {
        type filter hook input priority 0;
        policy accept;
    }

    chain forward {
        type filter hook forward priority 0;
        policy accept;
        # 允许已建立的连接
        ct state established,related accept
        # 放行转发到目标 IP 的端口范围
        ip daddr $DST_IP tcp dport $PORT_RANGE accept
        ip daddr $DST_IP udp dport $PORT_RANGE accept
    }

    chain output {
        type filter hook output priority 0;
        policy accept;
    }
}

table ip nat {
    chain prerouting {
        type nat hook prerouting priority 0;
        policy accept;
        # DNAT: 外部访问重定向到目标
        tcp dport $PORT_RANGE dnat to $DST_IP
        udp dport $PORT_RANGE dnat to $DST_IP
    }

    chain postrouting {
        type nat hook postrouting priority 100;
        policy accept;
        # SNAT: 改源地址为出口 IP
        ip daddr $DST_IP snat to $OUT_SRC_IP
    }
}
EOF

systemctl enable nftables --now
systemctl restart nftables

echo "✅ 转发规则已写入 /etc/nftables.conf 并永久生效。"
