#!/bin/bash
# 全局 TCP 透明代理脚本（HTTP 认证代理）
# 代理信息
PROXY_IP="45.199.243.175"
PROXY_PORT="64935"
PROXY_USER="QbkXJg9f4"
PROXY_PASS="1wg4hBDZf"

echo ">>> 安装 redsocks 和 iptables 持久化..."
apt update -y
apt install -y redsocks iptables-persistent

echo ">>> 写入 /etc/redsocks.conf ..."
cat > /etc/redsocks.conf <<EOF
base {
 log_debug = off;
 log_info = on;
 daemon = on;
 redirector = iptables;
}

redsocks {
 local_ip = 127.0.0.1;
 local_port = 12345;
 ip = $PROXY_IP;
 port = $PROXY_PORT;
 type = http-relay;
 login = "$PROXY_USER";
 password = "$PROXY_PASS";
}
EOF

echo ">>> 启动 redsocks 并设置开机自启..."
systemctl enable redsocks --now

echo ">>> 清空原有 nat 规则并重建 REDSOCKS 链..."
iptables -t nat -F
iptables -t nat -X REDSOCKS 2>/dev/null || true
iptables -t nat -N REDSOCKS

echo ">>> REDSOCKS 链：绕过本地/内网/代理本身..."
# 回环、本机
iptables -t nat -A REDSOCKS -d 127.0.0.0/8 -j RETURN
# 常见内网网段
iptables -t nat -A REDSOCKS -d 10.0.0.0/8 -j RETURN
iptables -t nat -A REDSOCKS -d 172.16.0.0/12 -j RETURN
iptables -t nat -A REDSOCKS -d 192.168.0.0/16 -j RETURN
iptables -t nat -A REDSOCKS -d 100.64.0.0/10 -j RETURN
# 代理服务器本身，不走代理，避免死循环
iptables -t nat -A REDSOCKS -d $PROXY_IP -j RETURN

echo ">>> REDSOCKS 链：其余 TCP 一律重定向到 12345 (redsocks)..."
iptables -t nat -A REDSOCKS -p tcp -j REDIRECT --to-ports 12345

echo ">>> OUTPUT 链：所有非 redsocks 进程发出的 TCP 流量 -> REDSOCKS ..."
iptables -t nat -A OUTPUT -p tcp -m owner ! --uid-owner redsocks -j REDSOCKS

echo ">>> 保存 iptables 规则..."
netfilter-persistent save || iptables-save > /etc/iptables.rules

echo ">>> 完成：当前机器所有 TCP 流量（含 XR VPN 出口）都走代理：$PROXY_IP:$PROXY_PORT"
echo ">>> 可测试：curl ip.sb  看看是不是代理出口 IP"
