#!/bin/bash
# ====================================================
#  Debian 12 全能脚本: 无弹窗静默安装版
#  配置: MTU=1380 | DNS定制 | Win兼容 | 8 IP
#  功能: 自动跳过 Yes/No 弹窗，部署完直接用
# ====================================================

# --- 0. 静默安装设置 (关键修正) ---
export DEBIAN_FRONTEND=noninteractive
# 预先回答 iptables-persistent 的 "Yes" 问题
echo iptables-persistent iptables-persistent/autosave_v4 boolean true | debconf-set-selections
echo iptables-persistent iptables-persistent/autosave_v6 boolean true | debconf-set-selections

# --- 1. 核心变量定义 ---
ETH0_IF="eth0"
ETH1_IF="eth1"

# Xray 信息 (Socks5)
XRAY_PORT=23456
XRAY_USER="admin"         # Socks5 用户名
XRAY_PASS="wawacloud"
XRAY_URL="http://wawaok.cn/static/xray"

# L2TP 信息
PSK_KEY="wawacloud"
VPN_PASS="wawacloud"      # L2TP 用户密码

# IP 定义 (根据您的最新规划)
# eth0 (主网卡) 的 IP 组: .10(主), .12, .13, .14
IP_ETH0_LIST="192.168.0.10 192.168.0.12 192.168.0.13 192.168.0.14"
# eth1 (副网卡) 的 IP 组: .11(主), .15, .16, .17
IP_ETH1_LIST="192.168.0.11 192.168.0.15 192.168.0.16 192.168.0.17"

# 定义有序列表 (用于 L2TP User1-User8 的顺序映射)
ORDERED_IPS="192.168.0.10 192.168.0.11 192.168.0.12 192.168.0.13 192.168.0.14 192.168.0.15 192.168.0.16 192.168.0.17"

# 所有 IP 汇总
ALL_IPS="$IP_ETH0_LIST $IP_ETH1_LIST"
ETH0_PRIMARY_IP=$(awk '{print $1}' <<< "$IP_ETH0_LIST")
ETH1_PRIMARY_IP=$(awk '{print $1}' <<< "$IP_ETH1_LIST")

# 路径定义
NET_SCRIPT="/usr/local/bin/configure_network.sh"
XRAY_DIR="/etc/xray"
XRAY_BIN="/usr/local/bin/xray"
OUTPUT_FILE="/root/socks5_L2TP.txt"

detect_gateway() {
    local iface="$1"
    local fallback_ip="$2"
    local gateway

    gateway=$(ip route show default dev "$iface" | awk '/default/ {print $3; exit}')
    if [[ -z "$gateway" && -n "$fallback_ip" ]]; then
        gateway=$(awk -F. '{print $1 "." $2 "." $3 ".1"}' <<< "$fallback_ip")
    fi
    echo "$gateway"
}

# --- 2. 系统初始化 ---
if [ "$EUID" -ne 0 ]; then echo "❌ 请以 root 运行"; exit; fi
echo "📦 [1/8] 更新系统并安装依赖 (静默模式)..."
apt-get update -q
# 安装 debconf-utils 用于自动应答
apt-get install -y debconf-utils
# 安装其他依赖
apt-get install wget curl iproute2 strongswan xl2tpd ppp net-tools iptables-persistent -y -q

echo "🧩 [1.5/8] 应用多网卡内核参数..."
cat > /etc/sysctl.d/99-wawacloud-multi-nic.conf <<EOF
net.ipv4.ip_forward = 1
net.ipv4.conf.all.rp_filter = 0
net.ipv4.conf.default.rp_filter = 0
net.ipv4.conf.all.arp_ignore = 1
net.ipv4.conf.all.arp_announce = 2
net.ipv4.conf.default.arp_ignore = 1
net.ipv4.conf.default.arp_announce = 2
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
EOF
sysctl --system >/dev/null

ETH1_GATEWAY=$(detect_gateway "$ETH1_IF" "$ETH1_PRIMARY_IP")
if [[ -z "$ETH1_GATEWAY" ]]; then
    echo "❌ 无法识别 $ETH1_IF 的网关，请检查网络配置后重试。"
    exit 1
fi

# --- 3. 配置持久化网络 ---
echo "🌐 [2/8] 配置网络与路由策略..."
cat > "$NET_SCRIPT" <<EOF
#!/bin/bash
set -e

ip link set $ETH0_IF up
ip link set $ETH1_IF up

# 多网卡同网段时，关闭严格反向路径校验并收敛 ARP 行为，避免副 IP 偶发不通
sysctl -w net.ipv4.conf.all.rp_filter=0 >/dev/null
sysctl -w net.ipv4.conf.default.rp_filter=0 >/dev/null
sysctl -w net.ipv4.conf.all.arp_ignore=1 >/dev/null
sysctl -w net.ipv4.conf.all.arp_announce=2 >/dev/null
sysctl -w net.ipv4.conf.default.arp_ignore=1 >/dev/null
sysctl -w net.ipv4.conf.default.arp_announce=2 >/dev/null
for iface in $ETH0_IF $ETH1_IF; do
    sysctl -w net.ipv4.conf.\$iface.rp_filter=0 >/dev/null
    sysctl -w net.ipv4.conf.\$iface.arp_ignore=1 >/dev/null
    sysctl -w net.ipv4.conf.\$iface.arp_announce=2 >/dev/null
done

# 绑定 eth0 IP
for ip in $IP_ETH0_LIST; do ip addr add \$ip/24 dev $ETH0_IF 2>/dev/null || true; done
# 绑定 eth1 IP
for ip in $IP_ETH1_LIST; do ip addr add \$ip/24 dev $ETH1_IF 2>/dev/null || true; done

# 配置策略路由 (让 eth1 流量正常回传)
if ! grep -q "200 eth1_rt" /etc/iproute2/rt_tables; then
    echo "200 eth1_rt" >> /etc/iproute2/rt_tables
fi
ip route flush table 200 2>/dev/null || true
ip route add $(awk -F. '{print $1 "." $2 "." $3 ".0/24"}' <<< "$ETH1_PRIMARY_IP") dev $ETH1_IF src $ETH1_PRIMARY_IP table 200 2>/dev/null || true
ip route replace default via $ETH1_GATEWAY dev $ETH1_IF table 200

# 清理旧规则
for src in $IP_ETH1_LIST 10.10.10.11 10.10.10.15 10.10.10.16 10.10.10.17; do
    while ip rule show | grep -q "from \$src lookup 200"; do
        ip rule del from \$src table 200 2>/dev/null || break
    done
done

# 添加规则: eth1 的 IP 走表 200
for ip in $IP_ETH1_LIST; do
    ip rule add from \$ip table 200 priority 100
done

# 添加规则: L2TP 对应走 eth1 的用户 (User2, User6, User7, User8)
# User2 -> .11
ip rule add from 10.10.10.11 table 200 priority 110
# User6 -> .15
ip rule add from 10.10.10.15 table 200 priority 110
# User7 -> .16
ip rule add from 10.10.10.16 table 200 priority 110
# User8 -> .17
ip rule add from 10.10.10.17 table 200 priority 110

ip route flush cache
EOF
chmod +x "$NET_SCRIPT"
bash "$NET_SCRIPT"

# 绑定结果校验：若 IP 未真正挂载，xray 监听会失败
IP_BIND_FAIL=0
for ip in $ALL_IPS; do
    if ! ip -o -4 addr show | awk '{print $4}' | cut -d/ -f1 | grep -qx "$ip"; then
        echo "❌ 内网 IP 未绑定成功: $ip"
        IP_BIND_FAIL=1
    fi
done
if [ "$IP_BIND_FAIL" -eq 1 ]; then
    echo "❌ 网络初始化失败，请先确认网卡名是否为 $ETH0_IF/$ETH1_IF，再重试。"
    exit 1
fi

# 网络自启
cat > /etc/systemd/system/custom-network.service <<EOF
[Unit]
Description=Custom Network Setup
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
ExecStart=$NET_SCRIPT
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable custom-network.service

# --- 4. 安装配置 Xray ---
echo "👻 [3/8] 安装配置 Xray SOCKS5..."
mkdir -p "$XRAY_DIR"
if [ ! -f "$XRAY_BIN" ]; then
    wget -O "$XRAY_BIN" "$XRAY_URL"
    chmod +x "$XRAY_BIN"
fi

# 校验 xray 二进制可执行，避免下载到 HTML/错误文件导致服务启动失败
if ! "$XRAY_BIN" version >/dev/null 2>&1; then
    echo "⚠️ Xray 二进制校验失败，尝试重新下载..."
    wget -O "$XRAY_BIN" "$XRAY_URL"
    chmod +x "$XRAY_BIN"
fi
if ! "$XRAY_BIN" version >/dev/null 2>&1; then
    echo "❌ Xray 二进制仍无效: $XRAY_BIN"
    exit 1
fi

cat > "$XRAY_DIR/config.json" <<EOF
{
  "log": { "loglevel": "warning" },
  "inbounds": [
EOF
FIRST=1
for IP in $ALL_IPS; do
  if [ "$FIRST" -ne 1 ]; then echo "," >> "$XRAY_DIR/config.json"; fi
  FIRST=0
  cat >> "$XRAY_DIR/config.json" <<EOF
    {
      "tag": "in-$IP", "port": $XRAY_PORT, "listen": "$IP", "protocol": "socks",
      "settings": { "auth": "password", "accounts": [ { "user": "$XRAY_USER", "pass": "$XRAY_PASS" } ], "udp": true }
    }
EOF
done
cat >> "$XRAY_DIR/config.json" <<EOF
  ], "outbounds": [
EOF
FIRST=1
for IP in $ALL_IPS; do
  if [ "$FIRST" -ne 1 ]; then echo "," >> "$XRAY_DIR/config.json"; fi
  FIRST=0
  cat >> "$XRAY_DIR/config.json" <<EOF
    { "tag": "out-$IP", "protocol": "freedom", "sendThrough": "$IP", "settings": {} }
EOF
done
cat >> "$XRAY_DIR/config.json" <<EOF
  ], "routing": { "rules": [
EOF
FIRST=1
for IP in $ALL_IPS; do
  if [ "$FIRST" -ne 1 ]; then echo "," >> "$XRAY_DIR/config.json"; fi
  FIRST=0
  cat >> "$XRAY_DIR/config.json" <<EOF
      { "type": "field", "inboundTag": ["in-$IP"], "outboundTag": "out-$IP" }
EOF
done
cat >> "$XRAY_DIR/config.json" <<EOF
    ] } }
EOF

cat > /etc/systemd/system/xray.service <<EOF
[Unit]
Description=Xray Service
After=network-online.target custom-network.service
Wants=network-online.target
[Service]
Type=simple
User=root
PrivateNetwork=false
ExecStartPre=/bin/bash -c 'for ip in $ALL_IPS; do ip -4 addr show | grep -qw "\$ip" || exit 1; done'
ExecStart=$XRAY_BIN -c $XRAY_DIR/config.json
Restart=on-failure
RestartSec=3s
LimitNOFILE=infinity
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable xray
systemctl restart xray

# 自检 xray 运行与端口监听状态
if ! systemctl is-active --quiet xray; then
    echo "❌ xray 服务未正常启动，最近日志如下："
    journalctl -u xray -n 80 --no-pager
    exit 1
fi
if ! ss -lntp | grep -Eq ":$XRAY_PORT\\b"; then
    echo "⚠️ xray 未监听 SOCKS5 端口 $XRAY_PORT，尝试重新拉取指定 URL 后重试..."
    wget -O "$XRAY_BIN" "$XRAY_URL"
    chmod +x "$XRAY_BIN"
    systemctl restart xray
    sleep 1
fi
if ! ss -lntp | grep -Eq ":$XRAY_PORT\\b"; then
    echo "❌ xray 仍未监听 SOCKS5 端口 $XRAY_PORT"
    echo "----- xray status -----"
    systemctl status xray --no-pager -l || true
    echo "----- xray journal -----"
    journalctl -u xray -n 80 --no-pager || true
    echo "----- ss 23456 -----"
    ss -lntup | grep "$XRAY_PORT" || true
    echo "----- xray config path -----"
    ls -l "$XRAY_DIR/config.json" || true
    exit 1
fi

# --- 5. 安装配置 L2TP/IPsec ---
echo "🔒 [4/8] 配置 L2TP/IPsec..."
cat > /etc/ipsec.conf <<EOF
version 2.0
config setup
    charondebug="ike 1, knl 1, cfg 0"
    uniqueids=no

conn %default
    keyexchange=ikev1
    authby=secret
    type=transport
    ike=aes128-sha1-modp1024,3des-sha1-modp1024
    esp=aes128-sha1,3des-sha1
    forceencaps=yes
    fragmentation=yes
    pfs=no
    rekey=no
    dpdaction=clear
    dpddelay=30s
    dpdtimeout=120s
    keyingtries=%forever

conn L2TP-PSK-NAT
    left=%any
    leftprotoport=17/1701
    right=%any
    rightprotoport=17/%any
    auto=add
EOF
echo "%any %any : PSK \"$PSK_KEY\"" > /etc/ipsec.secrets

cat > /etc/xl2tpd/xl2tpd.conf <<EOF
[global]
listen-addr = $ETH0_PRIMARY_IP
port = 1701
auth file = /etc/ppp/chap-secrets
access control = no
[lns default]
ip range = 10.10.10.200-10.10.10.254
local ip = 10.10.10.1
require chap = yes
refuse pap = yes
require authentication = yes
name = l2tpd
ppp debug = no
pppoptfile = /etc/ppp/options.xl2tpd
length bit = yes
EOF

# 定制 DNS 119.29... + MTU 1380 + Windows 兼容
cat > /etc/ppp/options.xl2tpd <<EOF
require-mschap-v2
ipcp-accept-local
ipcp-accept-remote
ms-dns 223.5.5.5
ms-dns 114.114.114.114
asyncmap 0
noccp
auth
hide-password
mtu 1380
mru 1380
name l2tpd
proxyarp
lcp-echo-interval 30
lcp-echo-failure 4
connect-delay 5000
novj
novjccomp
nobsdcomp
nodeflate
refuse-pap
refuse-chap
refuse-mschap
refuse-eap
EOF

# 生成用户: User1 对应 10.10.10.10, User2 对应 .11 ...
cat > /etc/ppp/chap-secrets <<EOF
"user1" l2tpd "$VPN_PASS" 10.10.10.10
"user2" l2tpd "$VPN_PASS" 10.10.10.11
"user3" l2tpd "$VPN_PASS" 10.10.10.12
"user4" l2tpd "$VPN_PASS" 10.10.10.13
"user5" l2tpd "$VPN_PASS" 10.10.10.14
"user6" l2tpd "$VPN_PASS" 10.10.10.15
"user7" l2tpd "$VPN_PASS" 10.10.10.16
"user8" l2tpd "$VPN_PASS" 10.10.10.17
EOF

# --- 6. 防火墙与 NAT ---
echo "🔥 [5/8] 配置防火墙 SNAT 映射..."
cat > /etc/sysctl.d/99-vpn.conf <<EOF
net.ipv4.ip_forward = 1
net.ipv4.conf.all.rp_filter = 0
net.ipv4.conf.default.rp_filter = 0
net.ipv4.conf.all.arp_ignore = 1
net.ipv4.conf.all.arp_announce = 2
net.ipv4.conf.default.arp_ignore = 1
net.ipv4.conf.default.arp_announce = 2
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
EOF
sysctl --system
iptables -I INPUT -p udp --dport 500 -j ACCEPT
iptables -I INPUT -p udp --dport 4500 -j ACCEPT
iptables -I INPUT -p udp --dport 1701 -j ACCEPT
iptables -I INPUT -p tcp --dport $XRAY_PORT -j ACCEPT
iptables -I INPUT -p udp --dport $XRAY_PORT -j ACCEPT
iptables -I FORWARD -i ppp+ -j ACCEPT
iptables -I FORWARD -o ppp+ -j ACCEPT
iptables -t mangle -C FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu 2>/dev/null || \
iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu

# 严格 NAT 映射
iptables -t nat -A POSTROUTING -s 10.10.10.10/32 -o eth0 -j SNAT --to-source 192.168.0.10
iptables -t nat -A POSTROUTING -s 10.10.10.11/32 -o eth1 -j SNAT --to-source 192.168.0.11
iptables -t nat -A POSTROUTING -s 10.10.10.12/32 -o eth0 -j SNAT --to-source 192.168.0.12
iptables -t nat -A POSTROUTING -s 10.10.10.13/32 -o eth0 -j SNAT --to-source 192.168.0.13
iptables -t nat -A POSTROUTING -s 10.10.10.14/32 -o eth0 -j SNAT --to-source 192.168.0.14
iptables -t nat -A POSTROUTING -s 10.10.10.15/32 -o eth1 -j SNAT --to-source 192.168.0.15
iptables -t nat -A POSTROUTING -s 10.10.10.16/32 -o eth1 -j SNAT --to-source 192.168.0.16
iptables -t nat -A POSTROUTING -s 10.10.10.17/32 -o eth1 -j SNAT --to-source 192.168.0.17

netfilter-persistent save
rm -f /var/run/xl2tpd/l2tpd.control
systemctl restart strongswan-starter
systemctl restart xl2tpd
systemctl enable strongswan-starter
systemctl enable xl2tpd

# --- 7. 安装管理菜单 (wawacloud) ---
echo "🛠️ [7/8] 安装管理菜单 (wawacloud)..."
cat > /usr/local/bin/wawacloud <<'EOF'
#!/bin/bash
# 配置文件路径
XRAY_CONFIG="/etc/xray/config.json"
L2TP_SECRETS="/etc/ppp/chap-secrets"
IPSEC_SECRETS="/etc/ipsec.secrets"
ORDERED_IPS="192.168.0.10 192.168.0.11 192.168.0.12 192.168.0.13 192.168.0.14 192.168.0.15 192.168.0.16 192.168.0.17"

# 颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
PLAIN='\033[0m'

clear
echo -e "${YELLOW}=================================================${PLAIN}"
echo -e "${GREEN}          WawaCloud 服务器管理菜单${PLAIN}"
echo -e "${YELLOW}=================================================${PLAIN}"
echo -e "  1. 修改 Socks5 (Xray) 账号和密码"
echo -e "  2. 修改 Socks5 (Xray) 端口"
echo -e "  3. 修改 L2TP VPN 用户密码 (批量修改 user1-8)"
echo -e "  4. 修改 L2TP 预共享密钥 (PSK)"
echo -e "  5. 查看当前配置信息"
echo -e "  0. 退出"
echo -e "${YELLOW}=================================================${PLAIN}"
echo -n "请输入选项 [0-5]: "
read choice

case $choice in
    1)
        echo -e "\n${GREEN}>>> 正在修改 Socks5 配置...${PLAIN}"
        echo -n "请输入新用户名: "
        read new_user
        echo -n "请输入新密码: "
        read new_pass
        if [[ -z "$new_user" || -z "$new_pass" ]]; then echo -e "${RED}不能为空${PLAIN}"; exit 1; fi
        
        sed -i 's/"user": ".*"/"user": "'$new_user'"/g' $XRAY_CONFIG
        sed -i 's/"pass": ".*"/"pass": "'$new_pass'"/g' $XRAY_CONFIG
        
        systemctl restart xray
        echo -e "${GREEN}✅ Socks5 重启成功!${PLAIN}"
        ;;
    2)
        echo -e "\n${GREEN}>>> 正在修改 Socks5 端口...${PLAIN}"
        current_port=$(sed -n 's/.*"port"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$XRAY_CONFIG" | head -n 1)
        echo -e "当前端口: ${YELLOW}${current_port:-未知}${PLAIN}"
        echo -n "请输入新端口 (1-65535): "
        read new_port
        if [[ ! "$new_port" =~ ^[0-9]+$ ]] || (( new_port < 1 || new_port > 65535 )); then
            echo -e "${RED}端口格式错误，必须是 1-65535 的数字${PLAIN}"
            exit 1
        fi

        sed -i 's/"port"[[:space:]]*:[[:space:]]*[0-9]\+/"port": '$new_port'/g' "$XRAY_CONFIG"

        if [[ -n "$current_port" && "$current_port" != "$new_port" ]]; then
            while iptables -D INPUT -p tcp --dport "$current_port" -j ACCEPT 2>/dev/null; do :; done
            while iptables -D INPUT -p udp --dport "$current_port" -j ACCEPT 2>/dev/null; do :; done
        fi
        iptables -C INPUT -p tcp --dport "$new_port" -j ACCEPT 2>/dev/null || iptables -I INPUT -p tcp --dport "$new_port" -j ACCEPT
        iptables -C INPUT -p udp --dport "$new_port" -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport "$new_port" -j ACCEPT
        netfilter-persistent save >/dev/null 2>&1 || true

        systemctl restart xray
        if ! systemctl is-active --quiet xray; then
            echo -e "${RED}❌ Xray 重启失败，请检查配置${PLAIN}"
            journalctl -u xray -n 50 --no-pager
            exit 1
        fi

        if [[ -n "$current_port" && -f /root/socks5_L2TP.txt ]]; then
            sed -i "s#/${current_port}/#/${new_port}/#g" /root/socks5_L2TP.txt
        fi
        echo -e "${GREEN}✅ Socks5 端口已修改为 $new_port，并已重启 Xray。${PLAIN}"
        ;;
    3)
        echo -e "\n${GREEN}>>> 正在修改 L2TP 用户密码...${PLAIN}"
        echo -n "请输入新密码 (将应用于所有用户): "
        read new_pass
        if [[ -z "$new_pass" ]]; then echo -e "${RED}不能为空${PLAIN}"; exit 1; fi
        
        # 批量替换密码，保留前后的结构
        sed -i 's/l2tpd ".*" 10/l2tpd "'$new_pass'" 10/g' $L2TP_SECRETS
        
        rm -f /var/run/xl2tpd/l2tpd.control
        systemctl restart xl2tpd
        echo -e "${GREEN}✅ L2TP 重启成功! 所有用户密码已更新。${PLAIN}"
        ;;
    4)
        echo -e "\n${GREEN}>>> 修改 PSK 密钥...${PLAIN}"
        echo -n "请输入新密钥: "
        read new_psk
        if [[ -z "$new_psk" ]]; then echo -e "${RED}不能为空${PLAIN}"; exit 1; fi
        
        echo "%any %any : PSK \"$new_psk\"" > $IPSEC_SECRETS
        systemctl restart strongswan-starter
        systemctl restart xl2tpd
        echo -e "${GREEN}✅ 密钥更新并重启成功!${PLAIN}"
        ;;
    5)
        echo -e "\n${GREEN}>>> 正在查询当前配置信息...${PLAIN}"
        socks_port=$(sed -n 's/.*"port"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$XRAY_CONFIG" | head -n 1)
        socks_user=$(sed -n 's/.*"user"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$XRAY_CONFIG" | head -n 1)
        socks_pass=$(sed -n 's/.*"pass"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$XRAY_CONFIG" | head -n 1)
        psk=$(sed -n 's/.*PSK[[:space:]]*"\([^"]*\)".*/\1/p' "$IPSEC_SECRETS" | head -n 1)
        vpn_pass=$(awk 'NR==1 {gsub(/"/, "", $3); print $3}' "$L2TP_SECRETS")

        declare -A PUB_IP_MAP
        main_server_ip=""
        for int_ip in $ORDERED_IPS; do
            pub_ip=$(curl -s --interface "$int_ip" --connect-timeout 5 http://whatismyip.akamai.com)
            if [[ -z "$pub_ip" ]]; then
                pub_ip=$(curl -s --interface "$int_ip" --connect-timeout 5 http://ifconfig.me)
            fi
            if [[ -z "$pub_ip" ]]; then
                pub_ip="获取失败"
            fi
            PUB_IP_MAP["$int_ip"]="$pub_ip"
            if [[ -z "$main_server_ip" && "$pub_ip" != "获取失败" ]]; then
                main_server_ip="$pub_ip"
            fi
        done
        if [[ -z "$main_server_ip" ]]; then
            main_server_ip="获取失败"
        fi

        echo ""
        echo "==================== SOCKS5 信息 ===================="
        echo ""
        echo "格式: IP/端口/账号/密码"
        echo ""
        for int_ip in $ORDERED_IPS; do
            echo "${PUB_IP_MAP[$int_ip]}/${socks_port:-未识别}/${socks_user:-未识别}/${socks_pass:-未识别}"
        done

        echo ""
        echo ""
        echo "===================== L2TP 信息 ====================="
        echo ""
        echo "格式: 入口IP/账号/密码/密钥/出口IP"
        echo ""
        count=1
        for int_ip in $ORDERED_IPS; do
            echo "${main_server_ip}/user${count}/${vpn_pass:-未识别}/${psk:-未识别}/${PUB_IP_MAP[$int_ip]}"
            ((count++))
        done
        ;;
    0) exit 0 ;;
    *) echo -e "${RED}无效选项${PLAIN}" ;;
esac
EOF
chmod +x /usr/local/bin/wawacloud
ln -sf /usr/local/bin/wawacloud /usr/local/bin/wulongcloud

# --- 8. 生成定制格式的输出文件 ---
echo "🔍 [8/8] 正在生成 socks5_L2TP.txt ..."
> "$OUTPUT_FILE"

# 8.1 准备数据：检测所有内网 IP 对应的公网 IP
declare -A PUB_IP_MAP
MAIN_SERVER_IP="" 

for int_ip in $ORDERED_IPS; do
    pub_ip=$(curl -s --interface "$int_ip" --connect-timeout 5 http://whatismyip.akamai.com)
    if [[ -z "$pub_ip" ]]; then
        pub_ip=$(curl -s --interface "$int_ip" --connect-timeout 5 http://ifconfig.me)
    fi
    
    if [[ -n "$pub_ip" ]]; then
        echo "✅ 检测: 内网 $int_ip -> 公网 $pub_ip"
        PUB_IP_MAP["$int_ip"]="$pub_ip"
        if [[ "$int_ip" == "192.168.0.10" ]]; then MAIN_SERVER_IP="$pub_ip"; fi
    else
        echo "❌ 内网 $int_ip 获取公网IP失败"
        PUB_IP_MAP["$int_ip"]="获取失败"
    fi
done

if [[ -z "$MAIN_SERVER_IP" ]]; then
    for k in "${!PUB_IP_MAP[@]}"; do MAIN_SERVER_IP="${PUB_IP_MAP[$k]}"; break; done
fi

# 8.2 写入 Socks5 格式
echo "Socks5格式-切勿用于违法行为，仅可作为技术交流" >> "$OUTPUT_FILE"
echo "一切行为造成的后果由使用者承担" >> "$OUTPUT_FILE"
echo "IP/端口/用户名/密码" >> "$OUTPUT_FILE"

for int_ip in $ORDERED_IPS; do
    pub_ip="${PUB_IP_MAP[$int_ip]}"
    echo "$pub_ip/$XRAY_PORT/$XRAY_USER/$XRAY_PASS" >> "$OUTPUT_FILE"
done

echo "----------------------------------------" >> "$OUTPUT_FILE"

# 8.3 写入 L2TP 格式
# --- 8. 生成定制格式的输出文件 + 终端输出（按新格式） ---
echo "🔍 [8/8] 正在生成 socks5_L2TP.txt ..."
> "$OUTPUT_FILE"

# 8.1 准备数据：检测所有内网 IP 对应的公网 IP
declare -A PUB_IP_MAP
MAIN_SERVER_IP=""

for int_ip in $ORDERED_IPS; do
    pub_ip=$(curl -s --interface "$int_ip" --connect-timeout 5 http://whatismyip.akamai.com)
    if [[ -z "$pub_ip" ]]; then
        pub_ip=$(curl -s --interface "$int_ip" --connect-timeout 5 http://ifconfig.me)
    fi

    if [[ -n "$pub_ip" ]]; then
        echo "✅ 检测: 内网 $int_ip -> 公网 $pub_ip"
        PUB_IP_MAP["$int_ip"]="$pub_ip"
        if [[ "$int_ip" == "192.168.0.10" ]]; then MAIN_SERVER_IP="$pub_ip"; fi
    else
        echo "❌ 内网 $int_ip 获取公网IP失败"
        PUB_IP_MAP["$int_ip"]="获取失败"
    fi
done

# 我是代码注释：兜底入口IP（如果 192.168.0.10 没拿到，就拿第一个能拿到的）
if [[ -z "$MAIN_SERVER_IP" ]]; then
    for k in $ORDERED_IPS; do
        if [[ "${PUB_IP_MAP[$k]}" != "获取失败" && -n "${PUB_IP_MAP[$k]}" ]]; then
            MAIN_SERVER_IP="${PUB_IP_MAP[$k]}"
            break
        fi
    done
fi
# 我是代码注释：再兜底（全失败时）
if [[ -z "$MAIN_SERVER_IP" ]]; then
    MAIN_SERVER_IP="获取失败"
fi

# 8.2 写入 SOCKS5 段（新格式）
{
    echo ""
    echo "==================== SOCKS5 信息 ===================="
    echo ""
    echo "格式: IP/端口/账号/密码"
    echo ""

    for int_ip in $ORDERED_IPS; do
        pub_ip="${PUB_IP_MAP[$int_ip]}"
        echo "${pub_ip}/${XRAY_PORT}/${XRAY_USER}/${XRAY_PASS}"
    done

    echo ""
    echo ""
    echo "===================== L2TP 信息 ====================="
    echo ""
    echo "格式: 入口IP/账号/密码/密钥/出口IP"
    echo ""

    count=1
    for int_ip in $ORDERED_IPS; do
        pub_ip="${PUB_IP_MAP[$int_ip]}"
        echo "${MAIN_SERVER_IP}/user${count}/${VPN_PASS}/${PSK_KEY}/${pub_ip}"
        ((count++))
    done

    echo ""
    echo ""
    echo "======================================================"
    echo ""
    echo "免责声明：仅用于合法合规的网络技术交流用途。"
    echo "使用者需自行承担一切行为责任。"
    echo ""
    echo "+--------------------------------------------------+"
    echo "| 官方交流群 / 联系方式"
    echo "+--------------------------------------------------+"
    echo "| 天翼云4.5折交流群：159500025"
    echo "| 华为云8.8折交流群：916383784"
    echo "| 火山引擎交流群：1051985214"
    echo "+--------------------------------------------------+"
    echo "| 技术微信：lywwyjs"
    echo "+--------------------------------------------------+"
    echo ""
} >> "$OUTPUT_FILE"

echo "✅✅✅ 全部完成！"
echo "[√] 结果已保存到: $OUTPUT_FILE"
echo "[√] 管理菜单已安装，输入 'wawacloud' 即可使用"
cat "$OUTPUT_FILE"
