#!/bin/bash
# 轻量版：多 IP Socks5 + 网关优化（无 backports、零报错）
set -eo pipefail
export DEBIAN_FRONTEND=noninteractive

#####################################
# 参数
#####################################
BASE_PORT=51000
S5_USER="vipuser"
S5_PASS="vip@123123"
XRAY_ZIP_URL="https://github.com/XTLS/Xray-core/releases/latest/download/Xray-linux-64.zip"
XRAY_BIN="/usr/local/bin/xray"
XRAY_CONF_DIR="/etc/xray"
XRAY_CONF_FILE="${XRAY_CONF_DIR}/config.json"

#####################################
# 0. 必须 root
#####################################
if [ "$(id -u)" -ne 0 ]; then
    echo "必须用 root 运行"
    exit 1
fi

#####################################
# 1. APT 基础安装（无 backports）
#####################################
#echo "===== 安装依赖 ====="
#apt install -y vim wget curl unzip net-tools lrzsz \
#  ethtool irqbalance conntrack iproute2 chrony bc

#####################################
# 2. 时间同步
#####################################
timedatectl set-timezone Asia/Shanghai
systemctl enable --now chrony || true

#####################################
# 3. 自动识别 WAN 接口
#####################################
auto_detect_wan() {
  ip route get 1.1.1.1 2>/dev/null | awk '/ dev /{for(i=1;i<=NF;i++){if($i=="dev"){print $(i+1); exit}}}'
}

WAN=$(auto_detect_wan)
echo "[info] 检测到 WAN 接口: $WAN"

#####################################
# 4. sysctl 优化
#####################################
echo "===== sysctl 优化 ====="
cat >/etc/sysctl.d/99-sysctl.conf <<'EOF'
# 基础转发
net.ipv4.ip_forward = 1
net.ipv6.conf.all.forwarding = 1
# RP filter
net.ipv4.conf.all.rp_filter = 2
net.ipv4.conf.default.rp_filter = 2
# SYN/连接队列
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 250000
net.ipv4.tcp_max_syn_backlog = 32768
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syncookies = 1
# TIME_WAIT/端口
net.ipv4.ip_local_port_range = 10100 65535
net.ipv4.tcp_fin_timeout = 15
# 缓冲区
net.core.rmem_default = 262144
net.core.wmem_default = 262144
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.optmem_max = 65536
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
net.ipv4.tcp_ecn=1
net.ipv4.tcp_frto=1
net.ipv4.tcp_mtu_probing = 1
# 拥塞控制/队列
net.ipv4.tcp_congestion_control = bbr
net.core.default_qdisc = fq_codel
# ARP/邻居缓存
net.ipv4.neigh.default.gc_interval = 30
net.ipv4.neigh.default.gc_stale_time = 60
net.ipv4.neigh.default.gc_thresh1 = 4096
net.ipv4.neigh.default.gc_thresh2 = 32768
net.ipv4.neigh.default.gc_thresh3 = 65536
net.ipv6.neigh.default.gc_thresh1 = 2048
net.ipv6.neigh.default.gc_thresh2 = 16384
net.ipv6.neigh.default.gc_thresh3 = 32768
# 安全
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
# 连接跟踪
net.netfilter.nf_conntrack_max = 524288
net.netfilter.nf_conntrack_tcp_timeout_established = 1200
net.netfilter.nf_conntrack_tcp_timeout_close_wait = 60
net.netfilter.nf_conntrack_tcp_timeout_fin_wait = 120
net.netfilter.nf_conntrack_tcp_timeout_time_wait = 120
net.netfilter.nf_conntrack_tcp_timeout_syn_recv = 60
net.netfilter.nf_conntrack_tcp_timeout_syn_sent = 60
net.netfilter.nf_conntrack_udp_timeout = 15
net.netfilter.nf_conntrack_udp_timeout_stream = 60
net.netfilter.nf_conntrack_generic_timeout = 120
# 文件描述符
fs.file-max = 2000000
# 内存
vm.swappiness = 10
# 避免转发节点接受上游 RA/自动生成地址（按需）
net.ipv6.conf.all.accept_ra = 0
net.ipv6.conf.default.accept_ra = 0
# 可选：如果接口都用静态/手工分配，禁用自动地址生成
 net.ipv6.conf.all.autoconf = 0
 net.ipv6.conf.default.autoconf = 0
# IPv6 也建议关闭 ICMP 重定向接受
net.ipv6.conf.all.accept_redirects = 0
net.ipv6.conf.default.accept_redirects = 0

EOF

sysctl --system

#####################################
# 5. 网卡优化
#####################################
echo "===== 网卡优化 ====="
ethtool -G "$WAN" rx 4096 tx 4096 || true
ethtool -K "$WAN" gro on gso on tso on lro off rx on tx on || true

echo 32768 >/proc/sys/net/core/rps_sock_flow_entries
for q in /sys/class/net/"$WAN"/queues/rx-*; do
  echo 32768 >"$q/rps_flow_cnt" 2>/dev/null || true
done

systemctl enable --now irqbalance || true
tc qdisc replace dev "$WAN" root fq_codel || true

#####################################
# 6. 安装 Xray
#####################################
echo "===== 安装 Xray ====="
mkdir -p /var/log/xray
mkdir -p "$XRAY_CONF_DIR"

cd /tmp
rm -f Xray-linux-64.zip
wget -O Xray-linux-64.zip "$XRAY_ZIP_URL"
unzip -o Xray-linux-64.zip -d /usr/local/bin/
chmod +x "$XRAY_BIN"

#####################################
# 7. 自动识别 多 IP /24 段（>=2 个 IP 即可）
#####################################
echo "===== 自动识别多 IP 段 (>=2 IP) ====="

mapfile -t ALL_IPS < <(ip -4 addr show scope global | awk '/inet /{print $2}' | cut -d/ -f1)

declare -A COUNT LIST

for ip in "${ALL_IPS[@]}"; do
    pfx=$(echo "$ip" | awk -F. '{print $1"."$2"."$3}')
    cur=${COUNT["$pfx"]:-0}
    COUNT["$pfx"]=$((cur+1))
    LIST["$pfx"]+="$ip "
done

SOCKS_PREFIX=""
for pfx in "${!COUNT[@]}"; do
    # 这里从 >=3 改成了 >=2
    if [ "${COUNT[$pfx]}" -ge 2 ]; then
        SOCKS_PREFIX="$pfx"
        break
    fi
done

if [ -z "$SOCKS_PREFIX" ]; then
    echo "❌ 没找到有 ≥2 个 IP 的 /24 网段"
    echo "当前全局 IP：${ALL_IPS[*]}"
    exit 1
fi

echo "[OK] 发现多IP网段：$SOCKS_PREFIX.x"
SOCKS_IPS=(${LIST[$SOCKS_PREFIX]})
COUNT_IP=${#SOCKS_IPS[@]}
echo "该段内 IP：${SOCKS_IPS[*]}"

#####################################
# 8. 生成 Xray 配置
#####################################
echo "===== 生成 Xray Socks5 配置 ====="

{
cat <<EOF
{
"log":{"access":"/var/log/xray/access.log","error":"/var/log/xray/error.log","loglevel":"info"},
"inbounds":[
EOF

for idx in "${!SOCKS_IPS[@]}"; do
  ip=${SOCKS_IPS[$idx]}
  last=$(echo "$ip" | awk -F. '{print $4}')
  port=$((BASE_PORT + last))
  comma=$([ "$idx" -lt $((COUNT_IP-1)) ] && echo "," || echo "")
cat <<EOF
  {"tag":"socks-$last","protocol":"socks","listen":"$ip","port":$port,
   "settings":{"auth":"password","accounts":[{"user":"$S5_USER","pass":"$S5_PASS"}],"udp":true}}
$comma
EOF
done

cat <<EOF
],
"routing":{"rules":[
EOF

for idx in "${!SOCKS_IPS[@]}"; do
  ip=${SOCKS_IPS[$idx]}
  last=$(echo "$ip" | awk -F. '{print $4}')
  comma=$([ "$idx" -lt $((COUNT_IP-1)) ] && echo "," || echo "")
cat <<EOF
  {"inboundTag":["socks-$last"],"outboundTag":"direct-$last"}$comma
EOF
done

cat <<EOF
]},
"outbounds":[
EOF

for idx in "${!SOCKS_IPS[@]}"; do
  ip=${SOCKS_IPS[$idx]}
  last=$(echo "$ip" | awk -F. '{print $4}')
  comma=$([ "$idx" -lt $((COUNT_IP-1)) ] && echo "," || echo "")
cat <<EOF
  {"protocol":"freedom","tag":"direct-$last","sendThrough":"$ip"}$comma
EOF
done

cat <<EOF
]}
EOF
} > "$XRAY_CONF_FILE"

#####################################
# 9. 启动 Xray
#####################################
"$XRAY_BIN" -config "$XRAY_CONF_FILE" -test

cat >/etc/systemd/system/xray.service <<EOF
[Unit]
Description=Xray Multi-IP Socks5
After=network.target

[Service]
ExecStart=$XRAY_BIN -config $XRAY_CONF_FILE
Restart=always
LimitNOFILE=1000000

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable --now xray

echo "===== 完成！ ====="
echo "多 IP 段： $SOCKS_PREFIX.x"
echo "Xray 配置位置： $XRAY_CONF_FILE"
echo "用户名: $S5_USER  密码: $S5_PASS  起始基准端口: $BASE_PORT"

