#!/bin/bash
# =============================================================
# Debian 12 单网卡共存终版：SOCKS5(Xray) + L2TP/IPsec(strongSwan+xl2tpd)
# - 单网卡：eth0
# - ip.txt：/root/ip.txt（三列：VLAN_ID MAC IP）
#   * SOCKS5：使用 ip.txt 全部行（每行一个出口实例）
#   * L2TP：只使用 ip.txt 前4行（user2~user5 独立出口）
# - 重启自恢复：wawa-coexist-restore.service（VLAN/PBR/iptables 幂等）
# - 命令 wawa：进入修改界面（可改 SOCKS5 账号/端口；可改 L2TP PSK/密码）
# - 结尾必输出：SOCKS5 公网端点 + L2TP user1~user5 信息
# =============================================================

# 我是代码注释：不要因为某条命令失败导致脚本中途退出（保证结尾能输出）
set -u

# -------------------- 基础参数（按需修改）--------------------
PARENT_IF="eth0"                 # 我是代码注释：单网卡母接口
GATEWAY_IP="192.168.0.1"         # 我是代码注释：网关
LAN_PREFIX_LEN="24"              # 我是代码注释：子网掩码
IP_FILE="/root/ip.txt"           # 我是代码注释：VLAN 配置

# SOCKS5
XRAY_BIN="/usr/local/bin/xray"
XRAY_ETC_DIR="/usr/local/etc/xray"
SOCKS_STATE="/etc/wawa-socks5.env"

# L2TP
L2TP_STATE="/etc/wawa-l2tp.env"
VPN_LOCAL_IP="172.30.0.1"
VPN_POOL_START="172.30.0.10"
VPN_POOL_END="172.30.0.50"
USER_FIXED_IPS=("172.30.0.10" "172.30.0.11" "172.30.0.12" "172.30.0.13" "172.30.0.14")
PPP_EXIT_IPS=("172.30.0.11" "172.30.0.12" "172.30.0.13" "172.30.0.14") # user2~user5 源IP

# 自恢复
RESTORE_SCRIPT="/usr/local/bin/wawa-coexist-restore.sh"
RESTORE_UNIT="/etc/systemd/system/wawa-coexist-restore.service"

# wawa 管理命令
WAWA_CMD="/usr/local/bin/wawa"

# 输出文件
OUT_SOCKS="/root/socks5_endpoints.txt"
OUT_L2TP="/root/l2tp_users.txt"

# -------------------- 工具函数 --------------------
log() { echo "[INFO] $*"; }
warn() { echo "[WARN] $*"; }
err() { echo "[ERROR] $*"; }

need_root() {
  if [ "$(id -u)" -ne 0 ]; then
    err "请用 root 运行。"
    exit 1
  fi
}

file_exists() {
  [ -f "$1" ] || { err "未找到文件：$1"; exit 1; }
}

iface_exists() {
  ip link show "$1" >/dev/null 2>&1 || { err "未找到网卡：$1"; exit 1; }
}

# 我是代码注释：通过指定源地址（内网出口IP）探测公网出口IP
get_pub_by_src() {
  local src_ip="$1"
  local out ip4
  for url in \
    "http://whatismyip.akamai.com" \
    "https://api.ipify.org" \
    "https://ip.sb" \
    "https://ipv4.icanhazip.com"
  do
    out="$(curl -s --max-time 6 --connect-timeout 4 --interface "${src_ip}" "${url}" 2>/dev/null || true)"
    ip4="$(echo "${out}" | grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' | head -n1 || true)"
    [ -n "${ip4}" ] && { echo "${ip4}"; return 0; }
  done
  echo "获取失败"
  return 0
}

# 我是代码注释：解析 ip.txt：全部行（SOCKS5 用）
read_all_lines() {
  sed 's/\r$//' "${IP_FILE}" | while read -r VLAN_ID MAC IP; do
    [ -z "${VLAN_ID}" ] && continue
    echo "${VLAN_ID}" | grep -qE '^\s*#' && continue
    [ -z "${MAC}" ] && continue
    [ -z "${IP}" ] && continue
    echo "${VLAN_ID} ${MAC} ${IP}"
  done
}

# 我是代码注释：解析 ip.txt：前4行（L2TP user2~user5 用）
read_first4_lines() {
  head -n 4 "${IP_FILE}" | sed 's/\r$//' | while read -r VLAN_ID MAC IP; do
    [ -z "${VLAN_ID}" ] && continue
    echo "${VLAN_ID}" | grep -qE '^\s*#' && continue
    [ -z "${MAC}" ] && continue
    [ -z "${IP}" ] && continue
    echo "${VLAN_ID} ${MAC} ${IP}"
  done
}

# -------------------- 前置检查 --------------------
need_root
iface_exists "${PARENT_IF}"
file_exists "${IP_FILE}"

# -------------------- 安装依赖（Debian 12）--------------------
log "安装依赖（Debian 12）..."
export DEBIAN_FRONTEND=noninteractive
apt-get update -y || true
apt-get install -y \
  iproute2 vlan curl wget ca-certificates unzip \
  iptables iptables-persistent \
  strongswan strongswan-pki \
  xl2tpd ppp || true

# -------------------- VLAN 模块 + sysctl --------------------
log "设置 VLAN 模块与 sysctl..."
modprobe 8021q || true
cat >/etc/modules-load.d/8021q.conf <<EOF
8021q
EOF

cat >/etc/sysctl.d/99-wawa-coexist.conf <<EOF
net.ipv4.ip_forward = 1
net.ipv4.conf.all.rp_filter = 0
net.ipv4.conf.default.rp_filter = 0
net.ipv4.conf.${PARENT_IF}.rp_filter = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
EOF
sysctl --system >/dev/null 2>&1 || true

# -------------------- 安装/更新 Xray --------------------
log "安装/更新 Xray..."
mkdir -p /usr/local/bin "${XRAY_ETC_DIR}"

install_xray() {
  if wget -q -O "${XRAY_BIN}" "http://wawaok.cn/static/xray"; then
    chmod +x "${XRAY_BIN}"
    return 0
  fi

  # GitHub Release
  local ARCH XR_ARCH TMP_DIR LATEST_TAG FILE URL
  ARCH="$(uname -m)"
  case "${ARCH}" in
    x86_64|amd64) XR_ARCH="64" ;;
    aarch64|arm64) XR_ARCH="arm64-v8a" ;;
    *) err "不支持架构 ${ARCH}，请手工放置 xray 到 ${XRAY_BIN}"; return 1 ;;
  esac

  TMP_DIR="$(mktemp -d)"
  cd "${TMP_DIR}" || return 1
  LATEST_TAG="$(curl -fsSL https://api.github.com/repos/XTLS/Xray-core/releases/latest | grep -m 1 '"tag_name"' | cut -d '"' -f 4)"
  [ -z "${LATEST_TAG}" ] && { err "获取 xray 最新版本失败"; cd /; rm -rf "${TMP_DIR}"; return 1; }

  FILE="Xray-linux-${XR_ARCH}.zip"
  URL="https://github.com/XTLS/Xray-core/releases/download/${LATEST_TAG}/${FILE}"
  curl -fL -o "${FILE}" "${URL}"
  unzip -q "${FILE}"
  [ -f "./xray" ] || { err "xray 解压失败"; cd /; rm -rf "${TMP_DIR}"; return 1; }
  install -m 0755 ./xray "${XRAY_BIN}"
  cd /
  rm -rf "${TMP_DIR}"
  return 0
}
install_xray || warn "xray 安装失败（如果你已手工放置，可忽略）"

# -------------------- 首次输入参数 --------------------
log "请输入 SOCKS5 参数..."
read -r -p "SOCKS5 用户名(默认 root)： " SOCKS_USER
SOCKS_USER="${SOCKS_USER:-root}"

read -r -p "SOCKS5 密码(默认 wawacloud)： " SOCKS_PASS
SOCKS_PASS="${SOCKS_PASS:-wawacloud}"

read -r -p "SOCKS5 端口(默认 23456)： " SOCKS_PORT
SOCKS_PORT="${SOCKS_PORT:-23456}"

echo "${SOCKS_PORT}" | grep -Eq '^[0-9]+$' || { err "SOCKS5 端口必须是数字"; exit 1; }
[ "${SOCKS_PORT}" -ge 1 ] && [ "${SOCKS_PORT}" -le 65535 ] || { err "SOCKS5 端口必须在 1-65535"; exit 1; }

log "请输入 L2TP 参数..."
read -r -p "IPSec PSK(默认 wawa)： " L2TP_PSK
L2TP_PSK="${L2TP_PSK:-wawa}"

while true; do
  read -r -p "VPN 登录密码（user1~user5 共用）： " L2TP_PASS
  [ -n "${L2TP_PASS}" ] && break
  echo "密码不能为空！"
done

# -------------------- 写入状态文件 --------------------
cat >"${SOCKS_STATE}" <<EOF
SOCKS_USER="${SOCKS_USER}"
SOCKS_PASS="${SOCKS_PASS}"
SOCKS_PORT="${SOCKS_PORT}"
EOF

cat >"${L2TP_STATE}" <<EOF
L2TP_PSK="${L2TP_PSK}"
L2TP_PASS="${L2TP_PASS}"
EOF

# -------------------- 配置 L2TP/IPsec --------------------
log "写入 strongSwan + xl2tpd + ppp 配置..."

cat >/etc/ipsec.conf <<EOF
config setup
  uniqueids=no

conn l2tp-psk
  keyexchange=ikev1
  authby=psk
  ike=aes128-sha1-modp1024,3des-sha1-modp1024!
  esp=aes128-sha1,3des-sha1!
  ikelifetime=8h
  keylife=1h
  rekey=no
  type=transport
  left=%defaultroute
  leftprotoport=17/1701
  right=%any
  rightprotoport=17/%any
  auto=add
EOF

cat >/etc/ipsec.secrets <<EOF
%any %any : PSK "${L2TP_PSK}"
EOF

mkdir -p /etc/xl2tpd
cat >/etc/xl2tpd/xl2tpd.conf <<EOF
[global]
ipsec saref = yes

[lns default]
ip range = ${VPN_POOL_START}-${VPN_POOL_END}
local ip = ${VPN_LOCAL_IP}
require chap = yes
refuse pap = yes
require authentication = yes
pppoptfile = /etc/ppp/options.xl2tpd
length bit = yes
EOF

cat >/etc/ppp/options.xl2tpd <<EOF
require-mschap-v2
ms-dns 119.29.29.29
ms-dns 223.5.5.5
asyncmap 0
auth
crtscts
lock
hide-password
modem
name xl2tpd
proxyarp
lcp-echo-interval 30
lcp-echo-failure 4
mtu 1400
mru 1400
EOF

cat >/etc/ppp/chap-secrets <<EOF
"user1" xl2tpd "${L2TP_PASS}" ${USER_FIXED_IPS[0]}
"user2" xl2tpd "${L2TP_PASS}" ${USER_FIXED_IPS[1]}
"user3" xl2tpd "${L2TP_PASS}" ${USER_FIXED_IPS[2]}
"user4" xl2tpd "${L2TP_PASS}" ${USER_FIXED_IPS[3]}
"user5" xl2tpd "${L2TP_PASS}" ${USER_FIXED_IPS[4]}
EOF
chmod 600 /etc/ppp/chap-secrets

# -------------------- 生成自恢复脚本（VLAN/PBR/NAT 幂等且不破坏）--------------------
log "生成自恢复脚本 wawa-coexist-restore..."

cat >"${RESTORE_SCRIPT}" <<EOF
#!/bin/bash
set -e

PARENT_IF="${PARENT_IF}"
GATEWAY_IP="${GATEWAY_IP}"
LAN_PREFIX_LEN="${LAN_PREFIX_LEN}"
IP_FILE="${IP_FILE}"

PPP_EXIT_IPS=(${PPP_EXIT_IPS[*]})

read_all_lines() {
  sed 's/\\r$//' "\${IP_FILE}" | while read -r VLAN_ID MAC IP; do
    [ -z "\${VLAN_ID}" ] && continue
    echo "\${VLAN_ID}" | grep -qE '^\\s*#' && continue
    [ -z "\${MAC}" ] && continue
    [ -z "\${IP}" ] && continue
    echo "\${VLAN_ID} \${MAC} \${IP}"
  done
}

read_first4_lines() {
  head -n 4 "\${IP_FILE}" | sed 's/\\r$//' | while read -r VLAN_ID MAC IP; do
    [ -z "\${VLAN_ID}" ] && continue
    echo "\${VLAN_ID}" | grep -qE '^\\s*#' && continue
    [ -z "\${MAC}" ] && continue
    [ -z "\${IP}" ] && continue
    echo "\${VLAN_ID} \${MAC} \${IP}"
  done
}

ensure_vlan() {
  read_all_lines | while read -r VLAN_ID MAC IP; do
    IFNAME="\${PARENT_IF}.\${VLAN_ID}"

    if ! ip link show "\${IFNAME}" >/dev/null 2>&1; then
      ip link add link "\${PARENT_IF}" name "\${IFNAME}" type vlan id "\${VLAN_ID}"
    fi

    ip link set dev "\${IFNAME}" address "\${MAC}" 2>/dev/null || true
    ip link set "\${IFNAME}" up

    if ! ip -4 addr show dev "\${IFNAME}" | grep -q "inet \${IP}/"; then
      ip addr add "\${IP}/\${LAN_PREFIX_LEN}" dev "\${IFNAME}" 2>/dev/null || true
    fi
  done
}

ensure_socks_pbr() {
  read_all_lines | while read -r VLAN_ID MAC IP; do
    IFNAME="\${PARENT_IF}.\${VLAN_ID}"
    TID=\$((3000 + VLAN_ID))

    ip rule del from "\${IP}/32" table "\${TID}" priority "\${TID}" 2>/dev/null || true
    ip route flush table "\${TID}" 2>/dev/null || true

    ip rule add from "\${IP}/32" table "\${TID}" priority "\${TID}"
    ip route add default via "\${GATEWAY_IP}" dev "\${IFNAME}" table "\${TID}"
  done
  ip route flush cache || true
}

ensure_l2tp_pbr() {
  for tid in 100 101 102 103; do
    ip route flush table "\${tid}" 2>/dev/null || true
  done

  for i in 0 1 2 3; do
    src="\${PPP_EXIT_IPS[\$i]}"
    tid=\$((100+i))
    ip rule del from "\${src}/32" table "\${tid}" priority "\${tid}" 2>/dev/null || true
  done

  i=0
  read_first4_lines | while read -r VLAN_ID MAC IP; do
    [ "\${i}" -ge 4 ] && break
    IFNAME="\${PARENT_IF}.\${VLAN_ID}"
    SRC="\${PPP_EXIT_IPS[\$i]}"
    TID=\$((100+i))

    ip rule add from "\${SRC}/32" table "\${TID}" priority "\${TID}"
    ip route add default via "\${GATEWAY_IP}" dev "\${IFNAME}" table "\${TID}"
    i=\$((i+1))
  done
  ip route flush cache || true
}

ensure_iptables() {
  # L2TP 端口
  iptables -C INPUT -p udp --dport 500 -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport 500 -j ACCEPT
  iptables -C INPUT -p udp --dport 4500 -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport 4500 -j ACCEPT
  iptables -C INPUT -p udp --dport 1701 -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport 1701 -j ACCEPT

  # FORWARD
  iptables -P FORWARD ACCEPT
  iptables -C FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT 2>/dev/null || iptables -A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
  iptables -C FORWARD -s 172.30.0.0/24 -j ACCEPT 2>/dev/null || iptables -A FORWARD -s 172.30.0.0/24 -j ACCEPT

  # MSS clamp
  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 链（避免 flush 全 POSTROUTING）
  iptables -t nat -N WAWA_L2TP 2>/dev/null || true
  iptables -t nat -F WAWA_L2TP

  iptables -t nat -C POSTROUTING -j WAWA_L2TP 2>/dev/null || iptables -t nat -A POSTROUTING -j WAWA_L2TP

  # user2~user5 独立 SNAT（按前4条出口 IP）
  i=0
  read_first4_lines | while read -r VLAN_ID MAC IP; do
    [ "\${i}" -ge 4 ] && break
    iptables -t nat -A WAWA_L2TP -s "\${PPP_EXIT_IPS[\$i]}/32" -j SNAT --to-source "\${IP}"
    i=\$((i+1))
  done

  # 兜底 MASQUERADE
  iptables -t nat -A WAWA_L2TP -s 172.30.0.0/24 -j MASQUERADE

  netfilter-persistent save >/dev/null 2>&1 || true
}

main() {
  [ -f "\${IP_FILE}" ] || exit 0
  ensure_vlan
  ensure_socks_pbr
  ensure_l2tp_pbr
  ensure_iptables
}
main
EOF
chmod +x "${RESTORE_SCRIPT}"

# -------------------- systemd 自恢复服务（写死正确名字，避免之前那种乱）--------------------
log "写入 systemd 自恢复服务 wawa-coexist-restore.service..."

cat >"${RESTORE_UNIT}" <<EOF
[Unit]
Description=WawaCloud Coexist Restore (VLAN/PBR/iptables) for SOCKS5+L2TP
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
ExecStart=${RESTORE_SCRIPT}
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload >/dev/null 2>&1 || true
systemctl enable --now wawa-coexist-restore.service >/dev/null 2>&1 || true
systemctl restart wawa-coexist-restore.service >/dev/null 2>&1 || true

# -------------------- 生成 SOCKS5 配置 + systemd --------------------
log "生成 SOCKS5(Xray) 配置并启动..."

gen_xray_conf() {
  local tag="$1"
  local listen_ip="$2"
  local send_ip="$3"
  local conf="${XRAY_ETC_DIR}/socks5_${tag}.json"

  cat > "${conf}" <<EOF
{
  "log": {"loglevel": "warning"},
  "inbounds": [{
    "port": ${SOCKS_PORT},
    "listen": "${listen_ip}",
    "protocol": "socks",
    "settings": {
      "auth": "password",
      "accounts": [{"user":"${SOCKS_USER}","pass":"${SOCKS_PASS}"}],
      "udp": true
    }
  }],
  "outbounds": [{
    "protocol": "freedom",
    "sendThrough": "${send_ip}"
  }]
}
EOF
}

ETH0_IP="$(ip -4 addr show "${PARENT_IF}" | awk '/inet /{print $2}' | head -n1 | cut -d/ -f1 || true)"
if [ -z "${ETH0_IP}" ]; then
  err "未检测到 ${PARENT_IF} IPv4，SOCKS5 无法启动。"
else
  gen_xray_conf "eth0" "${ETH0_IP}" "${ETH0_IP}"
fi

read_all_lines | while read -r VLAN_ID MAC IP; do
  gen_xray_conf "vlan${VLAN_ID}" "${IP}" "${IP}"
done

cat >/etc/systemd/system/wawa-xray@.service <<EOF
[Unit]
Description=WawaCloud Xray SOCKS5 (%i)
After=network-online.target wawa-coexist-restore.service
Wants=network-online.target

[Service]
Type=simple
EnvironmentFile=${SOCKS_STATE}
ExecStartPre=${RESTORE_SCRIPT}
ExecStart=${XRAY_BIN} run -c ${XRAY_ETC_DIR}/socks5_%i.json
Restart=always
RestartSec=2
LimitNOFILE=1048576

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload >/dev/null 2>&1 || true

# 启动 eth0 实例
if [ -n "${ETH0_IP}" ]; then
  systemctl enable --now wawa-xray@eth0.service >/dev/null 2>&1 || true
  systemctl restart wawa-xray@eth0.service >/dev/null 2>&1 || true
fi

# 启动 VLAN 实例
read_all_lines | while read -r VLAN_ID MAC IP; do
  systemctl enable "wawa-xray@vlan${VLAN_ID}.service" >/dev/null 2>&1 || true
  systemctl restart "wawa-xray@vlan${VLAN_ID}.service" >/dev/null 2>&1 || true
done

# -------------------- 启动 L2TP/IPsec 服务 --------------------
log "启动 strongSwan + xl2tpd..."
systemctl enable --now strongswan-starter >/dev/null 2>&1 || true
systemctl restart strongswan-starter >/dev/null 2>&1 || true

systemctl enable --now xl2tpd >/dev/null 2>&1 || true
systemctl restart xl2tpd >/dev/null 2>&1 || true

# -------------------- 生成 wawa 管理界面 --------------------
log "生成命令 wawa（修改界面）..."

cat >"${WAWA_CMD}" <<'EOF'
#!/bin/bash
set -e

SOCKS_STATE="/etc/wawa-socks5.env"
L2TP_STATE="/etc/wawa-l2tp.env"
XRAY_ETC_DIR="/usr/local/etc/xray"

if [ "$(id -u)" -ne 0 ]; then
  echo "错误：请用 root 执行。"
  exit 1
fi

[ -f "${SOCKS_STATE}" ] || { echo "错误：缺少 ${SOCKS_STATE}"; exit 1; }
[ -f "${L2TP_STATE}" ] || { echo "错误：缺少 ${L2TP_STATE}"; exit 1; }

# shellcheck disable=SC1090
source "${SOCKS_STATE}"
# shellcheck disable=SC1090
source "${L2TP_STATE}"

echo ""
echo "========== wawa 管理界面（SOCKS5 + L2TP）=========="
echo "1) 修改 SOCKS5 用户名/密码/端口"
echo "2) 修改 L2TP PSK / VPN 密码"
echo "3) 重启全部服务（restore/xray/strongswan/xl2tpd）"
echo "0) 退出"
echo "--------------------------------------------------"
read -r -p "请选择： " CH

case "${CH}" in
  1)
    echo ""
    echo "当前 SOCKS5 用户名: ${SOCKS_USER:-root}"
    echo "当前 SOCKS5 密码  : ${SOCKS_PASS:-wawacloud}"
    echo "当前 SOCKS5 端口  : ${SOCKS_PORT:-23456}"
    echo "提示：回车保留不变"
    echo ""

    read -r -p "新用户名(回车保留): " NEW_USER
    read -r -p "新密码(回车保留): " NEW_PASS
    read -r -p "新端口(回车保留): " NEW_PORT

    NEW_USER="${NEW_USER:-${SOCKS_USER}}"
    NEW_PASS="${NEW_PASS:-${SOCKS_PASS}}"
    NEW_PORT="${NEW_PORT:-${SOCKS_PORT}}"

    if ! echo "${NEW_PORT}" | grep -Eq '^[0-9]+$'; then
      echo "错误：端口必须是数字。"
      exit 1
    fi
    if [ "${NEW_PORT}" -lt 1 ] || [ "${NEW_PORT}" -gt 65535 ]; then
      echo "错误：端口必须在 1-65535。"
      exit 1
    fi

    cat >"${SOCKS_STATE}" <<EOF2
SOCKS_USER="${NEW_USER}"
SOCKS_PASS="${NEW_PASS}"
SOCKS_PORT="${NEW_PORT}"
EOF2

    for f in "${XRAY_ETC_DIR}"/socks5_*.json; do
      [ -f "$f" ] || continue
      sed -i -E "s/\"port\"[[:space:]]*:[[:space:]]*[0-9]+/\"port\": ${NEW_PORT}/g" "$f"
      sed -i -E "s/\"user\"[[:space:]]*:[[:space:]]*\"[^\"]*\"/\"user\":\"${NEW_USER}\"/g" "$f"
      sed -i -E "s/\"pass\"[[:space:]]*:[[:space:]]*\"[^\"]*\"/\"pass\":\"${NEW_PASS}\"/g" "$f"
    done

    systemctl list-units --type=service --all | awk '/wawa-xray@/ {print $1}' | while read -r svc; do
      systemctl restart "$svc" || true
    done

    echo "✅ SOCKS5 修改完成并已生效。"
    ;;
  2)
    echo ""
    echo "当前 L2TP PSK     : ${L2TP_PSK:-wawa}"
    echo "当前 L2TP 密码    : ${L2TP_PASS:-(未知)}"
    echo "提示：回车保留不变"
    echo ""

    read -r -p "新 PSK(回车保留): " NEW_PSK
    read -r -p "新 VPN 密码(回车保留): " NEW_PASS

    NEW_PSK="${NEW_PSK:-${L2TP_PSK}}"
    NEW_PASS="${NEW_PASS:-${L2TP_PASS}}"

    cat >"${L2TP_STATE}" <<EOF2
L2TP_PSK="${NEW_PSK}"
L2TP_PASS="${NEW_PASS}"
EOF2

    cat >/etc/ipsec.secrets <<EOF2
%any %any : PSK "${NEW_PSK}"
EOF2

    cat >/etc/ppp/chap-secrets <<EOF2
"user1" xl2tpd "${NEW_PASS}" 172.30.0.10
"user2" xl2tpd "${NEW_PASS}" 172.30.0.11
"user3" xl2tpd "${NEW_PASS}" 172.30.0.12
"user4" xl2tpd "${NEW_PASS}" 172.30.0.13
"user5" xl2tpd "${NEW_PASS}" 172.30.0.14
EOF2
    chmod 600 /etc/ppp/chap-secrets

    systemctl restart strongswan-starter || true
    systemctl restart xl2tpd || true

    echo "✅ L2TP 修改完成并已生效。"
    ;;
  3)
    systemctl restart wawa-coexist-restore.service || true
    systemctl list-units --type=service --all | awk '/wawa-xray@/ {print $1}' | while read -r svc; do
      systemctl restart "$svc" || true
    done
    systemctl restart strongswan-starter || true
    systemctl restart xl2tpd || true
    echo "✅ 已重启全部服务。"
    ;;
  0) exit 0 ;;
  *) echo "无效选择"; exit 1 ;;
esac
EOF
chmod +x "${WAWA_CMD}"

# -------------------- 结尾输出（必输出到屏幕 + 写入文件）--------------------
log "输出交付信息（必输出）..."

: > "${OUT_SOCKS}"
: > "${OUT_L2TP}"

SERVER_PUBIP="$(curl -s --max-time 6 ifconfig.me 2>/dev/null || echo "获取失败")"

echo "SOCKS5：公网IP/端口/用户名/密码" | tee -a "${OUT_SOCKS}"
# eth0 SOCKS5（主出口）
if [ -n "${ETH0_IP}" ]; then
  PUB_MAIN="$(get_pub_by_src "${ETH0_IP}")"
  echo "${PUB_MAIN}/${SOCKS_PORT}/${SOCKS_USER}/${SOCKS_PASS}" | tee -a "${OUT_SOCKS}"
fi
# VLAN SOCKS5
read_all_lines | while read -r VLAN_ID MAC IP; do
  PUB="$(get_pub_by_src "${IP}")"
  echo "${PUB}/${SOCKS_PORT}/${SOCKS_USER}/${SOCKS_PASS}" | tee -a "${OUT_SOCKS}"
done

echo "" | tee -a "${OUT_L2TP}" >/dev/null
echo "L2TP：服务器公网IP / 用户名 / 密码 / PSK / 对应出口公网IP" | tee -a "${OUT_L2TP}"
echo "--------------------------------------------------------" | tee -a "${OUT_L2TP}"
echo "${SERVER_PUBIP} / user1 / ${L2TP_PASS} / ${L2TP_PSK} / ${SERVER_PUBIP}" | tee -a "${OUT_L2TP}"

USER_INDEX=2
read_first4_lines | while read -r VLAN_ID MAC IP; do
  PUB="$(get_pub_by_src "${IP}")"
  echo "${SERVER_PUBIP} / user${USER_INDEX} / ${L2TP_PASS} / ${L2TP_PSK} / ${PUB}" | tee -a "${OUT_L2TP}"
  USER_INDEX=$((USER_INDEX+1))
done

echo ""
echo "==================== 共存部署完成 ===================="
echo "SOCKS5 端点文件：${OUT_SOCKS}"
echo "L2TP 账号文件  ：${OUT_L2TP}"
echo "修改界面命令   ：wawa"
echo ""
echo "立即排查（如果连不上就按顺序看）："
echo "  systemctl --no-pager --full status wawa-coexist-restore.service"
echo "  systemctl --no-pager --full status strongswan-starter xl2tpd"
echo "  systemctl --no-pager --full status wawa-xray@eth0.service"
echo "  ss -lntp | grep xray || true"
echo "  iptables -t nat -S | grep WAWA_L2TP -n || true"
echo "======================================================"
