#!/bin/bash
#═══════════════════════════════════════════════════════════════════════════════
#  初雪节点一键部署脚本 v1.0 [服务端]
#
#  参考 mozisen/surge (Zyx0rx) 的双核心架构精简重写:
#    • Xray 核心:     VLESS+Reality (XTLS Vision)
#    • Sing-box 核心: Hysteria2 / AnyTLS / TUIC v5 / Shadowsocks 2022
#
#  特色 (老王/勇哥同类脚本的 IP 偏好设置):
#    • IPv4 / IPv6 独立开关 (关掉的一侧不监听、不出站、链接不生成)
#    • 出口偏好: 双栈默认 / 优先 IPv4 / 优先 IPv6 / 仅 IPv4 / 仅 IPv6
#      同时作用于 Xray freedom 出站 domainStrategy 和
#      sing-box 的 DNS strategy + 出站 domain_strategy。
#    • 菜单和命令行都能改, 改完自动重写配置并重启服务:
#        ./chuxue-node.sh --ipv4 off --ipv6 on --prefer ipv6
#        ./chuxue-node.sh --prefer ipv4 | dual | ipv6 | ipv4only | ipv6only
#        ./chuxue-node.sh --links | --status | --uninstall
#
#  配置目录: /etc/chuxue-node (权限 700, 凭据文件 600)
#  适配: Debian / Ubuntu / CentOS / Alpine (systemd 或 OpenRC)
#═══════════════════════════════════════════════════════════════════════════════
set -o pipefail

readonly CX_VERSION="1.0.0"
readonly CX_DIR="${CX_DIR:-/etc/chuxue-node}"
readonly CX_STATE="${CX_STATE:-$CX_DIR/state.conf}"
readonly CX_XRAY_JSON="${CX_XRAY_JSON:-$CX_DIR/xray.json}"
readonly CX_SINGBOX_JSON="${CX_SINGBOX_JSON:-$CX_DIR/singbox.json}"
readonly CX_CERT="${CX_CERT:-$CX_DIR/cert.pem}"
readonly CX_KEY="${CX_KEY:-$CX_DIR/key.pem}"
readonly CX_SNELL_CONF="$CX_DIR/snell.conf"
readonly XRAY_BIN="/usr/local/bin/xray"
readonly SINGBOX_BIN="/usr/local/bin/sing-box"
readonly SNELL_BIN="/usr/local/bin/snell-server-v6"
readonly SNELL_VERSION="6.0.0b4"
readonly XRAY_UNIT="cx-xray"
readonly SINGBOX_UNIT="cx-singbox"
readonly SNELL_UNIT="cx-snell"

# ---------- 默认状态 (会被 state.conf 覆盖) ----------
IPV4_ENABLED=1
IPV6_ENABLED=1
IP_PREFERENCE="dual"        # dual | ipv4 | ipv6 | ipv4only | ipv6only
CX_PROTOCOLS="vless,hy2,anytls,tuic,ss,snell"  # 启用的协议, 逗号分隔
NODE_NAME="初雪"              # 节点名称 (链接里显示的名字)
WARP_MODE="off"               # off | split (分流 AI/流媒体) | global (全局)
WARP_PRIVATE_KEY=""
WARP_PEER_PUBLIC_KEY="bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo="
WARP_ADDRESS_V4=""
WARP_ADDRESS_V6=""
WARP_ENDPOINT="engage.cloudflareclient.com:2408"
REALITY_PORT=42001
REALITY_SNI="addons.mozilla.org"
HY2_PORT=42002
ANYTLS_PORT=42003
TUIC_PORT=42004
SS_PORT=42005
SNELL_PORT=42006
UUID=""
REALITY_PRIVATE_KEY=""
REALITY_PUBLIC_KEY=""
REALITY_SHORT_ID=""
HY2_PASSWORD=""
ANYTLS_PASSWORD=""
TUIC_PASSWORD=""
SS_PASSWORD=""
SNELL_PSK=""

C_G='\033[0;32m'; C_Y='\033[0;33m'; C_R='\033[0;31m'; C_C='\033[0;36m'; C_N='\033[0m'
info()  { echo -e "${C_G}[+]${C_N} $*"; }
warn()  { echo -e "${C_Y}[!]${C_N} $*"; }
err()   { echo -e "${C_R}[-]${C_N} $*" >&2; }
title() { echo -e "\n${C_C}== $* ==${C_N}"; }

need_root() {
    if [[ $EUID -ne 0 ]]; then err "需要 root 运行: sudo $0"; exit 1; fi
}

# ---------- 状态存取 ----------
load_state() {
    [[ -f "$CX_STATE" ]] && source "$CX_STATE"
    return 0
}

save_state() {
    mkdir -p "$CX_DIR" && chmod 700 "$CX_DIR"
    cat > "$CX_STATE" <<EOF
IPV4_ENABLED=$IPV4_ENABLED
IPV6_ENABLED=$IPV6_ENABLED
IP_PREFERENCE=$IP_PREFERENCE
CX_PROTOCOLS=$CX_PROTOCOLS
NODE_NAME="$NODE_NAME"
WARP_MODE=$WARP_MODE
WARP_PRIVATE_KEY=$WARP_PRIVATE_KEY
WARP_PEER_PUBLIC_KEY=$WARP_PEER_PUBLIC_KEY
WARP_ADDRESS_V4=$WARP_ADDRESS_V4
WARP_ADDRESS_V6=$WARP_ADDRESS_V6
WARP_ENDPOINT=$WARP_ENDPOINT
REALITY_PORT=$REALITY_PORT
REALITY_SNI=$REALITY_SNI
HY2_PORT=$HY2_PORT
ANYTLS_PORT=$ANYTLS_PORT
TUIC_PORT=$TUIC_PORT
SS_PORT=$SS_PORT
SNELL_PORT=$SNELL_PORT
UUID=$UUID
REALITY_PRIVATE_KEY=$REALITY_PRIVATE_KEY
REALITY_PUBLIC_KEY=$REALITY_PUBLIC_KEY
REALITY_SHORT_ID=$REALITY_SHORT_ID
HY2_PASSWORD=$HY2_PASSWORD
ANYTLS_PASSWORD=$ANYTLS_PASSWORD
TUIC_PASSWORD=$TUIC_PASSWORD
SS_PASSWORD=$SS_PASSWORD
SNELL_PSK=$SNELL_PSK
EOF
    chmod 600 "$CX_STATE"
}

# 协议开关: proto_on vless|hy2|anytls|tuic|ss|snell
proto_on() {
    case ",$CX_PROTOCOLS," in
        *",$1,"*) return 0 ;;
        *) return 1 ;;
    esac
}
singbox_needed() { proto_on hy2 || proto_on anytls || proto_on tuic || proto_on ss; }

# ---------- IP 检测 ----------
detect_ipv4() { curl -4 -s --max-time 8 https://api-ipv4.ip.sb/ip 2>/dev/null \
    || curl -4 -s --max-time 8 https://ipv4.icanhazip.com 2>/dev/null; }
detect_ipv6() { curl -6 -s --max-time 8 https://api-ipv6.ip.sb/ip 2>/dev/null \
    || curl -6 -s --max-time 8 https://ipv6.icanhazip.com 2>/dev/null; }
PUBLIC_IPV4=""
PUBLIC_IPV6=""
detect_ips() {
    PUBLIC_IPV4="$(detect_ipv4 | tr -d ' \n')"
    PUBLIC_IPV6="$(detect_ipv6 | tr -d ' \n')"
    if [[ -z "$PUBLIC_IPV6" && $IPV6_ENABLED -eq 1 ]]; then
        warn "未检测到公网 IPv6, IPv6 开关自动关闭 (可在有 v6 后手动打开)"
        IPV6_ENABLED=0
    fi
    if [[ -z "$PUBLIC_IPV4" && $IPV4_ENABLED -eq 1 ]]; then
        warn "未检测到公网 IPv4, IPv4 开关自动关闭"
        IPV4_ENABLED=0
    fi
    if [[ $IPV4_ENABLED -eq 0 && $IPV6_ENABLED -eq 0 ]]; then
        err "IPv4/IPv6 都不可用, 无法继续"; exit 1
    fi
}

#═══════════════════════════════════════════════════════════════════════════════
#  IP 偏好映射 (纯函数, 可单独测试)
#
#  IP_PREFERENCE 取值:
#    dual      双栈默认 (不干预解析顺序)
#    ipv4      优先 IPv4 (优先 A 记录, v6 兜底)   ← 勇哥/老王脚本的「优先IPv4」
#    ipv6      优先 IPv6 (优先 AAAA, v4 兜底)
#    ipv4only  仅 IPv4 (不出 v6)
#    ipv6only  仅 IPv6 (不出 v4)
#  开关优先于偏好: 关掉的一侧会被强制成 only 另一侧。
#═══════════════════════════════════════════════════════════════════════════════
effective_preference() {
    if [[ $IPV4_ENABLED -eq 0 && $IPV6_ENABLED -eq 1 ]]; then echo "ipv6only"; return; fi
    if [[ $IPV6_ENABLED -eq 0 && $IPV4_ENABLED -eq 1 ]]; then echo "ipv4only"; return; fi
    echo "$IP_PREFERENCE"
}

# Xray freedom 出站 domainStrategy
xray_domain_strategy() {
    case "$(effective_preference)" in
        dual)     echo "AsIs" ;;
        ipv4)     echo "UseIPv4v6" ;;
        ipv6)     echo "UseIPv6v4" ;;
        ipv4only) echo "ForceIPv4" ;;
        ipv6only) echo "ForceIPv6" ;;
        *)        echo "AsIs" ;;
    esac
}

# sing-box DNS strategy / outbound domain_strategy
singbox_strategy() {
    case "$(effective_preference)" in
        dual)     echo "" ;;
        ipv4)     echo "prefer_ipv4" ;;
        ipv6)     echo "prefer_ipv6" ;;
        ipv4only) echo "ipv4_only" ;;
        ipv6only) echo "ipv6_only" ;;
        *)        echo "" ;;
    esac
}

# 监听地址: 双开或仅 v6 -> "::" (Linux 双栈通吃); 仅 v4 -> "0.0.0.0"
listen_addr() {
    if [[ $IPV4_ENABLED -eq 1 && $IPV6_ENABLED -eq 0 ]]; then
        echo "0.0.0.0"
    else
        echo "::"
    fi
}

# DNS 服务器 (跟随偏好选 v4/v6 的公共 DNS)
dns_servers_json_singbox() {
    local strategy; strategy="$(singbox_strategy)"
    local servers=""
    if [[ $IPV4_ENABLED -eq 1 ]]; then
        servers+='{"type":"udp","tag":"dns-v4","server":"223.5.5.5","server_port":53}'
    fi
    if [[ $IPV6_ENABLED -eq 1 ]]; then
        [[ -n "$servers" ]] && servers+=","
        servers+='{"type":"udp","tag":"dns-v6","server":"2400:3200::1","server_port":53}'
    fi
    local strat_json=""
    [[ -n "$strategy" ]] && strat_json=",\"strategy\":\"$strategy\""
    echo "{\"servers\":[$servers]$strat_json}"
}

# ---------- 依赖与核心安装 ----------
pkg_install() {
    if command -v apt-get >/dev/null; then
        apt-get update -y && apt-get install -y "$@"
    elif command -v dnf >/dev/null; then
        dnf install -y "$@"
    elif command -v yum >/dev/null; then
        yum install -y "$@"
    elif command -v apk >/dev/null; then
        apk add --no-cache "$@"
    else
        err "不支持的发行版"; exit 1
    fi
}

ensure_deps() {
    local missing=()
    for c in curl wget unzip openssl; do
        command -v "$c" >/dev/null || missing+=("$c")
    done
    if [[ ${#missing[@]} -gt 0 ]]; then
        info "安装依赖: ${missing[*]}"
        pkg_install "${missing[@]}"
    fi
    if ! command -v jq >/dev/null; then pkg_install jq || true; fi
}

arch_suffix() {
    case "$(uname -m)" in
        x86_64|amd64)  echo "amd64" ;;
        aarch64|arm64) echo "arm64" ;;
        *) err "不支持的架构: $(uname -m)"; exit 1 ;;
    esac
}

install_xray() {
    if [[ -x "$XRAY_BIN" ]]; then info "Xray 已安装: $($XRAY_BIN version | head -1)"; return; fi
    info "安装 Xray-core (官方脚本)..."
    bash -c "$(curl -fsSL https://github.com/XTLS/Xray-install/raw/main/install-release.sh)" \
        @ install --binary-only -u root >/dev/null 2>&1 || true
    if [[ ! -x "$XRAY_BIN" && -x /usr/local/bin/xray ]]; then :; fi
    [[ -x "$XRAY_BIN" ]] || { err "Xray 安装失败"; exit 1; }
    info "Xray 安装完成: $($XRAY_BIN version | head -1)"
}

install_singbox() {
    if [[ -x "$SINGBOX_BIN" ]]; then info "sing-box 已安装: $($SINGBOX_BIN version | head -1)"; return; fi
    info "安装 sing-box (GitHub Release, 带 sha256 校验)..."
    local arch; arch="$(arch_suffix)"
    local ver; ver="$(curl -fsSL https://api.github.com/repos/SagerNet/sing-box/releases/latest \
        | grep '"tag_name"' | head -1 | sed -E 's/.*"v?([^"]+)".*/\1/')"
    [[ -n "$ver" ]] || { err "获取 sing-box 版本失败"; exit 1; }
    local name="sing-box-${ver}-linux-${arch}"
    local url="https://github.com/SagerNet/sing-box/releases/download/v${ver}/${name}.tar.gz"
    local tmp; tmp="$(mktemp -d)"
    curl -fsSL -o "$tmp/pkg.tar.gz" "$url" || { err "sing-box 下载失败"; exit 1; }
    # 官方 .tar.gz 附带同名 .sha256? 以发布页校验文件为准, 下载失败则跳过校验并提示
    if curl -fsSL -o "$tmp/pkg.sha256" "${url}.sha256" 2>/dev/null; then
        (cd "$tmp" && sha256sum -c pkg.sha256 >/dev/null) \
            && info "sing-box sha256 校验通过" || { err "sha256 校验失败"; exit 1; }
    else
        warn "未取到官方校验文件, 跳过 sha256 校验"
    fi
    tar -xzf "$tmp/pkg.tar.gz" -C "$tmp"
    install -m 755 "$tmp/$name/sing-box" "$SINGBOX_BIN"
    rm -rf "$tmp"
    info "sing-box 安装完成: $($SINGBOX_BIN version | head -1)"
}

install_snell() {
    if [[ -x "$SNELL_BIN" ]]; then info "Snell v6 已安装"; return 0; fi
    info "安装 Snell v6 server v$SNELL_VERSION (Surge 官方分发)..."
    local arch; arch="$(arch_suffix)"
    local url="https://dl.nssurge.com/snell/snell-server-v${SNELL_VERSION}-linux-${arch}.zip"
    local tmp; tmp="$(mktemp -d)"
    if ! curl -fsSL -o "$tmp/snell.zip" "$url"; then
        warn "Snell v6 下载失败, 跳过 Snell (其余协议不受影响)"; rm -rf "$tmp"; return 1
    fi
    # 已知版本的内置 sha256 (与官方 GitHub 镜像資產一致, 校验不过则拒绝安装)
    local pinned=""
    case "$SNELL_VERSION:$arch" in
        6.0.0b4:amd64)   pinned="d66891cffc9f1b24a7b959ffbd2c4a246013f4f9e612733027b5ad106ce5f87f" ;;
        6.0.0b4:arm64)   pinned="2c957ee6bb37ce4b1df2b6a23e652b75546d10bc4f0443a2928e5834ae0429af" ;;
    esac
    if [[ -n "$pinned" ]]; then
        if ! echo "$pinned  $tmp/snell.zip" | sha256sum -c - >/dev/null 2>&1; then
            warn "Snell v6 sha256 校验失败, 跳过 Snell"; rm -rf "$tmp"; return 1
        fi
        info "Snell v6 sha256 校验通过"
    fi
    unzip -o "$tmp/snell.zip" -d "$tmp" >/dev/null || { warn "Snell 解压失败, 跳过"; rm -rf "$tmp"; return 1; }
    install -m 755 "$tmp/snell-server" "$SNELL_BIN" || { warn "Snell 安装失败, 跳过"; rm -rf "$tmp"; return 1; }
    rm -rf "$tmp"
    info "Snell v6 安装完成"
    return 0
}

# ---------- 快捷指令 cx ----------
readonly CX_SHORTCUT="/usr/local/bin/cx"
ensure_shortcut() {
    local self
    self="$(readlink -f "${BASH_SOURCE[0]}" 2>/dev/null || echo "")"
    [[ -n "$self" && -f "$self" ]] || return 0
    [[ "$self" == "$CX_SHORTCUT" ]] && return 0
    if install -m 755 "$self" "$CX_SHORTCUT" 2>/dev/null; then
        info "快捷指令已安装: 以后直接输入 cx 打开脚本"
    fi
}

# ---------- 安装时的名称/端口询问 ----------
# 节点名清洗: 去掉空格/引号/URL 特殊字符, 保留中英文、数字、-_.
sanitize_name() {
    echo "$1" | tr -d ' \t"'"'"'\\$`#?&/' | head -c 40
}

# 随机高位端口 (20000-60000), 避开已选端口和正在监听的端口
random_port() {
    local p tries=0
    while (( tries < 60 )); do
        if command -v shuf >/dev/null 2>&1; then
            p="$(shuf -i 20000-60000 -n 1)"
        else
            p=$(( 20000 + (RANDOM * 32768 + RANDOM) % 40001 ))
        fi
        case " $REALITY_PORT $HY2_PORT $ANYTLS_PORT $TUIC_PORT $SS_PORT $SNELL_PORT " in
            *" $p "*) tries=$((tries+1)); continue ;;
        esac
        if command -v ss >/dev/null 2>&1 && ss -tuln 2>/dev/null | grep -q ":$p[[:space:]]"; then
            tries=$((tries+1)); continue
        fi
        echo "$p"; return 0
    done
    echo "$(( 20000 + (RANDOM * 32768 + RANDOM) % 40001 ))"
}

ask_port() {
    local label="$1" var="$2" input
    read -rp "$label 端口 [回车=随机高位端口]: " input || input=""
    if [[ -z "$input" ]]; then
        printf -v "$var" '%s' "$(random_port)"
        info "$label 端口: ${!var} (随机)"
    elif [[ "$input" =~ ^[0-9]+$ ]] && (( input >= 1 && input <= 65535 )); then
        printf -v "$var" '%s' "$input"
        info "$label 端口: ${!var}"
    else
        warn "端口无效: $input, 改用随机端口"
        printf -v "$var" '%s' "$(random_port)"
        info "$label 端口: ${!var} (随机)"
    fi
}

# 全新安装时询问节点名和各协议端口; 已有 state (重装) 时不问, 沿用旧值。
# 非交互运行 (无 tty) 也不问, 用默认值/命令行参数。CX_FORCE_PROMPT=1 可强制询问。
prompt_install_config() {
    [[ "${CX_WIZARD_DONE:-0}" == "1" ]] && return 0
    [[ -f "$CX_STATE" ]] && return 0
    if [[ ! -t 0 && "${CX_FORCE_PROMPT:-0}" != "1" ]]; then return 0; fi
    title "节点设置 (直接回车 = 默认)"
    local name_in=""
    read -rp "节点名称 [$NODE_NAME]: " name_in || name_in=""
    name_in="$(sanitize_name "$name_in")"
    [[ -n "$name_in" ]] && NODE_NAME="$name_in"
    info "节点名称: $NODE_NAME"
    proto_on vless  && ask_port "VLESS Reality" REALITY_PORT
    proto_on hy2    && ask_port "Hysteria2" HY2_PORT
    proto_on anytls && ask_port "AnyTLS" ANYTLS_PORT
    proto_on tuic   && ask_port "TUIC" TUIC_PORT
    proto_on ss     && ask_port "SS2022" SS_PORT
    proto_on snell  && ask_port "Snell v6" SNELL_PORT
    return 0
}

# ---------- 搭建节点向导 (菜单第 1 项) ----------
CX_WIZARD_DONE=0

# 向导版端口询问: 全新安装回车=随机; 已装机器回车=保持当前, 输入 r=随机, 数字=指定
ask_port_wizard() {
    local label="$1" var="$2" fresh="$3" input cur
    cur="${!var}"
    if [[ "$fresh" == "1" ]]; then
        read -rp "$label 端口 [回车=随机高位端口]: " input || input=""
        if [[ -z "$input" ]]; then
            printf -v "$var" '%s' "$(random_port)"; info "$label 端口: ${!var} (随机)"
        elif [[ "$input" =~ ^[0-9]+$ ]] && (( input >= 1 && input <= 65535 )); then
            printf -v "$var" '%s' "$input"; info "$label 端口: ${!var}"
        else
            warn "端口无效: $input, 改用随机端口"; printf -v "$var" '%s' "$(random_port)"; info "$label 端口: ${!var} (随机)"
        fi
    else
        read -rp "$label 端口 [当前 $cur, 回车=不变, r=随机]: " input || input=""
        if [[ -z "$input" ]]; then
            info "$label 端口: $cur (不变)"
        elif [[ "$input" == "r" || "$input" == "R" ]]; then
            printf -v "$var" '%s' "$(random_port)"; info "$label 端口: ${!var} (随机)"
        elif [[ "$input" =~ ^[0-9]+$ ]] && (( input >= 1 && input <= 65535 )); then
            printf -v "$var" '%s' "$input"; info "$label 端口: ${!var}"
        else
            warn "端口无效: $input, 保持不变"
        fi
    fi
}

install_wizard() {
    local fresh=0
    [[ -f "$CX_STATE" ]] || fresh=1
    title "搭建节点"
    # 1) 选协议 (可多选) — 排序: SS 第一, VLESS 第二, Snell 第三, 其余随意
    echo "选择要搭建的协议 (可多选, 逗号或空格分隔, 回车=保持当前: $CX_PROTOCOLS)"
    echo "  1) SS2022          2) VLESS+Reality   3) Snell v6"
    echo "  4) Hysteria2       5) AnyTLS          6) TUIC v5"
    local pin=""
    read -rp "协议编号: " pin || pin=""
    if [[ -n "$pin" ]]; then
        local list="" n
        for n in $(echo "$pin" | tr ',' ' '); do
            case "$n" in
                1) list="${list}ss," ;;
                2) list="${list}vless," ;;
                3) list="${list}snell," ;;
                4) list="${list}hy2," ;;
                5) list="${list}anytls," ;;
                6) list="${list}tuic," ;;
                *) warn "忽略无效编号: $n" ;;
            esac
        done
        list="${list%,}"
        [[ -n "$list" ]] && CX_PROTOCOLS="$list"
    fi
    info "已选协议: $CX_PROTOCOLS"
    # 2) 节点名称
    local name_in=""
    read -rp "节点名称 [$NODE_NAME]: " name_in || name_in=""
    name_in="$(sanitize_name "$name_in")"
    [[ -n "$name_in" ]] && NODE_NAME="$name_in"
    info "节点名称: $NODE_NAME"
    # 3) 各协议端口 (按协议排序: SS, VLESS, Snell, HY2, AnyTLS, TUIC)
    proto_on ss     && ask_port_wizard "SS2022" SS_PORT "$fresh"
    proto_on vless  && ask_port_wizard "VLESS Reality" REALITY_PORT "$fresh"
    proto_on snell  && ask_port_wizard "Snell v6" SNELL_PORT "$fresh"
    proto_on hy2    && ask_port_wizard "Hysteria2" HY2_PORT "$fresh"
    proto_on anytls && ask_port_wizard "AnyTLS" ANYTLS_PORT "$fresh"
    proto_on tuic   && ask_port_wizard "TUIC" TUIC_PORT "$fresh"
    # 4) VLESS 的 SNI 伪装域名
    if proto_on vless; then
        echo "Reality 伪装域名 SNI (回车=保持当前: $REALITY_SNI)"
        echo "  1) addons.mozilla.org   2) apps.apple.com"
        echo "  3) www.apple.com        4) gateway.icloud.com   5) 自定义输入"
        local sni_ch=""
        read -rp "SNI 选择: " sni_ch || sni_ch=""
        case "$sni_ch" in
            1) REALITY_SNI="addons.mozilla.org" ;;
            2) REALITY_SNI="apps.apple.com" ;;
            3) REALITY_SNI="www.apple.com" ;;
            4) REALITY_SNI="gateway.icloud.com" ;;
            5)
                local sni_in=""
                read -rp "输入 SNI 域名: " sni_in || sni_in=""
                [[ -n "$sni_in" ]] && REALITY_SNI="$sni_in"
                ;;
            "") : ;;
            *) warn "无效选择, 保持 $REALITY_SNI" ;;
        esac
        info "SNI: $REALITY_SNI"
    fi
    # 5) 出站 IP 偏好 (命名与勇哥 sing-box-yg 脚本一致)
    echo "出站 IP 偏好 (回车=保持当前: $IP_PREFERENCE)"
    echo "  1) 双栈 (IPV4/IPV6 同时开启)   2) IPV4优先   3) IPV6优先"
    echo "  4) 仅IPV4                      5) 仅IPV6"
    local pch=""
    read -rp "偏好选择: " pch || pch=""
    case "$pch" in
        1) IP_PREFERENCE="dual" ;;
        2) IP_PREFERENCE="ipv4" ;;
        3) IP_PREFERENCE="ipv6" ;;
        4) IP_PREFERENCE="ipv4only" ;;
        5) IP_PREFERENCE="ipv6only" ;;
        "") : ;;
        *) warn "无效选择, 保持 $IP_PREFERENCE" ;;
    esac
    info "出站偏好: $IP_PREFERENCE"
    # 6) WARP 出站
    echo "WARP 出站 (Cloudflare 出口, 解锁 AI/流媒体; 回车=保持当前: $WARP_MODE)"
    echo "  1) 不启用   2) 分流 (仅 AI/流媒体域名走 WARP)   3) 全局 (全部流量走 WARP)"
    echo "  注: WARP 对 VLESS 和 sing-box 协议生效, Snell 仍直连"
    local wch=""
    read -rp "WARP 选择: " wch || wch=""
    case "$wch" in
        1) WARP_MODE="off" ;;
        2) WARP_MODE="split" ;;
        3) WARP_MODE="global" ;;
        "") : ;;
        *) warn "无效选择, 保持 $WARP_MODE" ;;
    esac
    info "WARP 模式: $WARP_MODE"
    CX_WIZARD_DONE=1
}

# ---------- 网络测试 (第三方脚本, 运行时下载执行) ----------
run_ip_quality() {
    title "IP质量测试 (xykt/IPQuality)"
    info "下载并运行: bash <(curl -Ls https://IP.Check.Place)"
    bash <(curl -Ls https://IP.Check.Place)
    read -rp "按回车返回菜单" _ || true
}

run_backtrace() {
    title "三网回程路线 (zhanghanyun/backtrace)"
    curl -sSf https://raw.githubusercontent.com/zhanghanyun/backtrace/main/install.sh | sh
}

run_superspeed() {
    title "三网测速 (oooldking/superspeed)"
    bash <(curl -Lso- https://raw.githubusercontent.com/oooldking/script/master/superspeed.sh)
}

network_test_menu() {
    while true; do
        title "三网回程路线/速度"
        echo " 1) 三网回程路线 (电信/联通/移动 回程线路类型)"
        echo " 2) 三网测速 (三网节点 上下行速度)"
        echo " 3) 两个都跑 (先回程路线, 再测速)"
        echo " 0) 返回"
        read -rp "选择: " ch
        case "$ch" in
            1) run_backtrace ;;
            2) run_superspeed ;;
            3) run_backtrace; run_superspeed ;;
            0) return ;;
            *) warn "无效选择"; continue ;;
        esac
        read -rp "按回车继续" _ || true
    done
}

# ---------- WARP (照 mozisen 脚本的 wgcf 方案改写) ----------
warp_on() { [[ "$WARP_MODE" == "split" || "$WARP_MODE" == "global" ]]; }

WGCF_VERSION="2.2.29"
install_wgcf() {
    command -v wgcf >/dev/null 2>&1 && return 0
    [[ -x /usr/local/bin/wgcf ]] && { export PATH="/usr/local/bin:$PATH"; return 0; }
    local arch; arch="$(uname -m)"
    local warch="amd64"
    case "$arch" in
        aarch64|arm64) warch="arm64" ;;
        armv7l) warch="armv7" ;;
    esac
    info "下载 wgcf v$WGCF_VERSION ($warch)..."
    local tmp; tmp="$(mktemp)"
    if curl -fsSL --connect-timeout 15 --max-time 120 -o "$tmp" \
        "https://github.com/ViRb3/wgcf/releases/download/v${WGCF_VERSION}/wgcf_${WGCF_VERSION}_linux_${warch}" \
        && [[ -s "$tmp" ]] && (( $(stat -c%s "$tmp" 2>/dev/null || echo 0) > 1000000 )); then
        install -m 755 "$tmp" /usr/local/bin/wgcf && rm -f "$tmp"
        info "wgcf 安装完成"
        return 0
    fi
    rm -f "$tmp"
    err "wgcf 下载失败"
    return 1
}

# 注册 WARP 账号 (wgcf register/generate), 解析 WireGuard 配置存入 state 变量
ensure_warp_account() {
    warp_on || return 0
    [[ -n "$WARP_PRIVATE_KEY" && -n "$WARP_ADDRESS_V4" ]] && return 0
    need_root
    install_wgcf || { warn "WARP 工具下载失败, 本次跳过 WARP"; WARP_MODE="off"; return 1; }
    local tmp old_pwd
    tmp="$(mktemp -d)" || return 1
    old_pwd="$PWD"
    cd "$tmp" || { rm -rf "$tmp"; return 1; }
    info "注册 Cloudflare WARP 账号..."
    if ! wgcf register --accept-tos >/dev/null 2>&1 || [[ ! -f wgcf-account.toml ]]; then
        err "WARP 账号注册失败"
        cd "$old_pwd" || true; rm -rf "$tmp"
        WARP_MODE="off"; return 1
    fi
    if ! wgcf generate >/dev/null 2>&1 || [[ ! -f wgcf-profile.conf ]]; then
        err "WARP 配置生成失败"
        cd "$old_pwd" || true; rm -rf "$tmp"
        WARP_MODE="off"; return 1
    fi
    WARP_PRIVATE_KEY="$(grep -i '^PrivateKey' wgcf-profile.conf | cut -d'=' -f2 | tr -d ' \r')"
    local pub; pub="$(grep -i '^PublicKey' wgcf-profile.conf | cut -d'=' -f2 | tr -d ' \r')"
    [[ -n "$pub" ]] && WARP_PEER_PUBLIC_KEY="$pub"
    local ep; ep="$(grep -i '^Endpoint' wgcf-profile.conf | cut -d'=' -f2 | tr -d ' \r')"
    [[ -n "$ep" ]] && WARP_ENDPOINT="$ep"
    local addrs; addrs="$(grep -i '^Address' wgcf-profile.conf | cut -d'=' -f2 | tr -d ' \r' | tr ',' '\n')"
    local a
    for a in $addrs; do
        if [[ "$a" == *:* ]]; then WARP_ADDRESS_V6="$a"; else WARP_ADDRESS_V4="$a"; fi
    done
    cd "$old_pwd" || true
    rm -rf "$tmp"
    if [[ -z "$WARP_PRIVATE_KEY" || -z "$WARP_ADDRESS_V4" ]]; then
        err "WARP 配置解析失败"
        WARP_MODE="off"; return 1
    fi
    info "WARP 账号就绪 (出口地址 $WARP_ADDRESS_V4)"
    return 0
}

# 分流域名 (AI + 流媒体, 后缀匹配)
WARP_SPLIT_DOMAINS="openai.com chatgpt.com oaistatic.com oaiusercontent.com claude.ai anthropic.com gemini.google.com ai.google.dev aistudio.google.com perplexity.ai copilot.microsoft.com bing.com netflix.com nflxvideo.net nflximg.net disneyplus.com hbomax.com hbo.com spotify.com scdn.co youtube.com googlevideo.com ytimg.com tiktok.com twitter.com x.com"

warp_domains_xray_json() {
    local out="" d
    for d in $WARP_SPLIT_DOMAINS; do out="${out}\"domain:${d}\","; done
    echo "${out%,}"
}

warp_domains_singbox_json() {
    local out="" d
    for d in $WARP_SPLIT_DOMAINS; do out="${out}\"${d}\","; done
    echo "${out%,}"
}

# Xray: WARP 出站 JSON (不带前后逗号, 调用处拼接); 无 WARP 时为空
xray_warp_outbound() {
    warp_on && [[ -n "$WARP_PRIVATE_KEY" ]] || return 0
    local addrs="\"$WARP_ADDRESS_V4\""
    [[ -n "$WARP_ADDRESS_V6" ]] && addrs="${addrs},\"$WARP_ADDRESS_V6\""
    local ds; ds="$(xray_domain_strategy)"
    local ds_json=""
    [[ "$ds" != "AsIs" ]] && ds_json=",\"domainStrategy\":\"$ds\""
    cat <<EOF
{"tag": "warp", "protocol": "wireguard", "settings": {"secretKey": "$WARP_PRIVATE_KEY", "address": [$addrs], "peers": [{"publicKey": "$WARP_PEER_PUBLIC_KEY", "allowedIPs": ["0.0.0.0/0", "::/0"], "endpoint": "$WARP_ENDPOINT"}], "reserved": [0, 0, 0], "mtu": 1280$ds_json}}
EOF
}

# Xray: WARP 路由规则 (保护规则 + 分流/全局), 每条以逗号结尾; 无 WARP 时为空
xray_warp_rules() {
    warp_on && [[ -n "$WARP_PRIVATE_KEY" ]] || return 0
    echo '{"type": "field", "domain": ["engage.cloudflareclient.com"], "outboundTag": "direct"},'
    if [[ "$WARP_MODE" == "split" ]]; then
        echo "{\"type\": \"field\", \"domain\": [$(warp_domains_xray_json)], \"outboundTag\": \"warp\"},"
    else
        echo '{"type": "field", "network": "tcp,udp", "outboundTag": "warp"},'
    fi
}

# sing-box: WARP endpoint JSON; 无 WARP 时为空
singbox_warp_endpoint() {
    warp_on && [[ -n "$WARP_PRIVATE_KEY" ]] || return 0
    local addrs="\"$WARP_ADDRESS_V4\""
    [[ -n "$WARP_ADDRESS_V6" ]] && addrs="${addrs},\"$WARP_ADDRESS_V6\""
    local ep_host="${WARP_ENDPOINT%:*}" ep_port="${WARP_ENDPOINT##*:}"
    ep_host="${ep_host#[}"; ep_host="${ep_host%]}"
    local strategy; strategy="$(singbox_strategy)"
    local ds_json=""
    if [[ -n "$strategy" ]]; then
        local rtag="dns-v4"
        [[ $IPV4_ENABLED -eq 0 && $IPV6_ENABLED -eq 1 ]] && rtag="dns-v6"
        ds_json=",\"domain_resolver\":{\"server\":\"$rtag\",\"strategy\":\"$strategy\"}"
    fi
    cat <<EOF
{"type": "wireguard", "tag": "warp", "address": [$addrs], "private_key": "$WARP_PRIVATE_KEY", "peers": [{"address": "$ep_host", "port": ${ep_port:-2408}, "public_key": "$WARP_PEER_PUBLIC_KEY", "allowed_ips": ["0.0.0.0/0", "::/0"], "reserved": [0, 0, 0], "persistent_keepalive_interval": 25}], "mtu": 1280$ds_json}
EOF
}

# sing-box: WARP 路由规则 (逗号结尾); global 模式改 final, 这里只出保护+分流规则
singbox_warp_rules() {
    warp_on && [[ -n "$WARP_PRIVATE_KEY" ]] || return 0
    echo '{"domain": ["engage.cloudflareclient.com"], "outbound": "direct"},'
    if [[ "$WARP_MODE" == "split" ]]; then
        echo "{\"domain_suffix\": [$(warp_domains_singbox_json)], \"outbound\": \"warp\"},"
    fi
}

warp_menu() {
    while true; do
        title "WARP 设置"
        echo "当前模式: $WARP_MODE  (off=不启用 split=分流 global=全局)"
        [[ -n "$WARP_ADDRESS_V4" ]] && echo "WARP 出口地址: $WARP_ADDRESS_V4"
        echo "说明: WARP 只对 Xray (VLESS) 和 sing-box (HY2/AnyTLS/TUIC/SS) 生效, Snell 仍直连"
        echo " 1) 不启用"
        echo " 2) 分流 (仅 AI/流媒体域名走 WARP)"
        echo " 3) 全局 (全部流量走 WARP)"
        echo " 0) 返回"
        read -rp "选择: " ch
        case "$ch" in
            1) WARP_MODE="off" ;;
            2) WARP_MODE="split" ;;
            3) WARP_MODE="global" ;;
            0) return ;;
            *) warn "无效选择"; continue ;;
        esac
        if warp_on; then ensure_warp_account || true; fi
        if warp_on && [[ -z "$WARP_PRIVATE_KEY" ]]; then
            warn "WARP 账号未就绪, 保持关闭"; WARP_MODE="off"; continue
        fi
        detect_ips
        apply_ip_settings
    done
}

gen_credentials() {
    [[ -z "$UUID" ]] && UUID="$(cat /proc/sys/kernel/random/uuid)"
    if [[ -z "$REALITY_PRIVATE_KEY" ]]; then
        local out; out="$($XRAY_BIN x25519)"
        REALITY_PRIVATE_KEY="$(echo "$out" | grep -i 'private' | awk '{print $NF}')"
        REALITY_PUBLIC_KEY="$(echo "$out" | grep -i 'public' | awk '{print $NF}')"
        REALITY_SHORT_ID="$(openssl rand -hex 8)"
    fi
    local rp; rp() { openssl rand -base64 24 | tr -d '/+=' | head -c 20; }
    [[ -z "$HY2_PASSWORD" ]]    && HY2_PASSWORD="$(rp)"
    [[ -z "$ANYTLS_PASSWORD" ]] && ANYTLS_PASSWORD="$(rp)"
    [[ -z "$TUIC_PASSWORD" ]]   && TUIC_PASSWORD="$(rp)"
    [[ -z "$SS_PASSWORD" ]]     && SS_PASSWORD="$(openssl rand -base64 32 | head -c 44)"
    [[ -z "$SNELL_PSK" ]]       && SNELL_PSK="$(openssl rand -base64 24 | tr -d '/+=' | head -c 24)"
}

gen_cert() {
    mkdir -p "$CX_DIR"
    if [[ -f "$CX_CERT" && -f "$CX_KEY" ]]; then return; fi
    info "生成自签证书 (HY2/AnyTLS/TUIC 用, 客户端需开启跳过验证)..."
    local san="IP:127.0.0.1"
    [[ -n "$PUBLIC_IPV4" ]] && san+=",IP:${PUBLIC_IPV4}"
    openssl req -x509 -newkey rsa:2048 -keyout "$CX_KEY" -out "$CX_CERT" \
        -days 3650 -nodes -subj "/CN=chuxue-node" -addext "subjectAltName=${san}" 2>/dev/null
    chmod 600 "$CX_KEY" "$CX_CERT"
}

# ---------- 配置生成 ----------
gen_xray_config() {
    mkdir -p "$CX_DIR"
    local listen; listen="$(listen_addr)"
    local strategy; strategy="$(xray_domain_strategy)"
    local warp_out warp_rules warp_outbounds=""
    warp_out="$(xray_warp_outbound)"
    warp_rules="$(xray_warp_rules)"
    [[ -n "$warp_out" ]] && warp_outbounds=", $warp_out"
    cat > "$CX_XRAY_JSON" <<EOF
{
  "log": {"loglevel": "warning"},
  "inbounds": [
    {
      "tag": "vless-reality",
      "listen": "$listen",
      "port": $REALITY_PORT,
      "protocol": "vless",
      "settings": {
        "clients": [{"id": "$UUID", "flow": "xtls-rprx-vision"}],
        "decryption": "none"
      },
      "streamSettings": {
        "network": "tcp",
        "security": "reality",
        "realitySettings": {
          "show": false,
          "dest": "${REALITY_SNI}:443",
          "xver": 0,
          "serverNames": ["$REALITY_SNI"],
          "privateKey": "$REALITY_PRIVATE_KEY",
          "shortIds": ["$REALITY_SHORT_ID"]
        }
      },
      "sniffing": {"enabled": true, "destOverride": ["http", "tls", "quic"]}
    }
  ],
  "outbounds": [
    {"tag": "direct", "protocol": "freedom", "settings": {"domainStrategy": "$strategy"}},
    {"tag": "block", "protocol": "blackhole"}$warp_outbounds
  ],
  "routing": {
    "domainStrategy": "IPIfNonMatch",
    "rules": [${warp_rules}{"type": "field", "ip": ["geoip:private"], "outboundTag": "block"}]
  }
}
EOF
    chmod 600 "$CX_XRAY_JSON"
}

gen_singbox_config() {
    mkdir -p "$CX_DIR"
    local listen; listen="$(listen_addr)"
    local strategy; strategy="$(singbox_strategy)"
    local dns; dns="$(dns_servers_json_singbox)"
    local outbound_strategy=""
    local resolver_tag="dns-v4"
    [[ $IPV4_ENABLED -eq 0 && $IPV6_ENABLED -eq 1 ]] && resolver_tag="dns-v6"
    [[ -n "$strategy" ]] && outbound_strategy=",\"domain_resolver\":{\"server\":\"$resolver_tag\",\"strategy\":\"$strategy\"}"
    local inbounds=()
    if proto_on hy2; then
        inbounds+=("{\"type\":\"hysteria2\",\"tag\":\"hy2-in\",\"listen\":\"$listen\",\"listen_port\":$HY2_PORT,\"users\":[{\"password\":\"$HY2_PASSWORD\"}],\"tls\":{\"enabled\":true,\"certificate_path\":\"$CX_CERT\",\"key_path\":\"$CX_KEY\"}}")
    fi
    if proto_on anytls; then
        inbounds+=("{\"type\":\"anytls\",\"tag\":\"anytls-in\",\"listen\":\"$listen\",\"listen_port\":$ANYTLS_PORT,\"users\":[{\"name\":\"cx\",\"password\":\"$ANYTLS_PASSWORD\"}],\"tls\":{\"enabled\":true,\"certificate_path\":\"$CX_CERT\",\"key_path\":\"$CX_KEY\"}}")
    fi
    if proto_on tuic; then
        inbounds+=("{\"type\":\"tuic\",\"tag\":\"tuic-in\",\"listen\":\"$listen\",\"listen_port\":$TUIC_PORT,\"users\":[{\"uuid\":\"$UUID\",\"password\":\"$TUIC_PASSWORD\"}],\"congestion_control\":\"bbr\",\"tls\":{\"enabled\":true,\"certificate_path\":\"$CX_CERT\",\"key_path\":\"$CX_KEY\",\"alpn\":[\"h3\"]}}")
    fi
    if proto_on ss; then
        inbounds+=("{\"type\":\"shadowsocks\",\"tag\":\"ss-in\",\"listen\":\"$listen\",\"listen_port\":$SS_PORT,\"method\":\"2022-blake3-aes-256-gcm\",\"password\":\"$SS_PASSWORD\"}")
    fi
    local inbounds_json; inbounds_json="$(IFS=,; echo "${inbounds[*]}")"
    local warp_ep warp_rules_sb endpoints_block="" route_final="direct"
    warp_ep="$(singbox_warp_endpoint)"
    warp_rules_sb="$(singbox_warp_rules)"
    [[ -n "$warp_ep" ]] && endpoints_block="\"endpoints\": [$warp_ep],"
    if warp_on && [[ -n "$WARP_PRIVATE_KEY" && "$WARP_MODE" == "global" ]]; then route_final="warp"; fi
    cat > "$CX_SINGBOX_JSON" <<EOF
{
  "log": {"level": "warn"},
  "dns": $dns,
  "inbounds": [$inbounds_json],
  $endpoints_block
  "outbounds": [
    {"type": "direct", "tag": "direct"$outbound_strategy},
    {"type": "block", "tag": "block"}
  ],
  "route": {"rules": [${warp_rules_sb}{"ip_is_private": true, "outbound": "block"}], "final": "$route_final", "default_domain_resolver": {"server": "$resolver_tag"}}
}
EOF
    chmod 600 "$CX_SINGBOX_JSON"
}

gen_snell_config() {
    mkdir -p "$CX_DIR"
    local listen; listen="$(listen_addr)"
    # Snell 的 ipv6 选项管的是出站: 偏好为仅 IPv4 出站 (或 v6 开关关) 时为 false
    local ipv6_enabled="false"
    if [[ $IPV6_ENABLED -eq 1 && "$(effective_preference)" != "ipv4only" ]]; then
        ipv6_enabled="true"
    fi
    local hostport
    if [[ "$listen" == "::" ]]; then hostport="[::]:$SNELL_PORT"; else hostport="0.0.0.0:$SNELL_PORT"; fi
    cat > "$CX_SNELL_CONF" <<EOF
[snell-server]
listen = $hostport
psk = $SNELL_PSK
ipv6 = $ipv6_enabled
obfs = off
EOF
    chmod 600 "$CX_SNELL_CONF"
}

# ---------- systemd / OpenRC ----------
write_services() {
    if command -v systemctl >/dev/null; then
        cat > "/etc/systemd/system/${XRAY_UNIT}.service" <<EOF
[Unit]
Description=Chuxue Xray (VLESS Reality)
After=network.target nss-lookup.target
[Service]
User=root
ExecStart=$XRAY_BIN run -c $CX_XRAY_JSON
Restart=on-failure
LimitNOFILE=1000000
[Install]
WantedBy=multi-user.target
EOF
        cat > "/etc/systemd/system/${SINGBOX_UNIT}.service" <<EOF
[Unit]
Description=Chuxue sing-box (HY2/AnyTLS/TUIC/SS2022)
After=network.target nss-lookup.target
[Service]
User=root
ExecStart=$SINGBOX_BIN run -c $CX_SINGBOX_JSON
Restart=on-failure
LimitNOFILE=1000000
[Install]
WantedBy=multi-user.target
EOF
        if [[ -x "$SNELL_BIN" ]]; then
            cat > "/etc/systemd/system/${SNELL_UNIT}.service" <<EOF
[Unit]
Description=Chuxue Snell v6
After=network.target nss-lookup.target
[Service]
User=root
ExecStart=$SNELL_BIN -c $CX_SNELL_CONF
Restart=on-failure
LimitNOFILE=1000000
[Install]
WantedBy=multi-user.target
EOF
        fi
        systemctl daemon-reload
        systemctl enable "${XRAY_UNIT}" "${SINGBOX_UNIT}" >/dev/null 2>&1 || true
        [[ -x "$SNELL_BIN" ]] && systemctl enable "${SNELL_UNIT}" >/dev/null 2>&1 || true
    elif command -v rc-service >/dev/null; then
        for unit in "$XRAY_UNIT" "$SINGBOX_UNIT"; do
            local bin="$XRAY_BIN"; [[ "$unit" == "$SINGBOX_UNIT" ]] && bin="$SINGBOX_BIN"
            local cfg="$CX_XRAY_JSON"; [[ "$unit" == "$SINGBOX_UNIT" ]] && cfg="$CX_SINGBOX_JSON"
            cat > "/etc/init.d/$unit" <<EOF
#!/sbin/openrc-run
name="$unit"
command="$bin"
command_args="run -c $cfg"
command_background="yes"
pidfile="/run/$unit.pid"
EOF
            chmod +x "/etc/init.d/$unit"
            rc-update add "$unit" default >/dev/null 2>&1 || true
        done
    fi
}

svc() { # svc <xray|singbox|snell> <restart|stop|status>
    local unit="$XRAY_UNIT"
    [[ "$1" == "singbox" ]] && unit="$SINGBOX_UNIT"
    [[ "$1" == "snell" ]] && unit="$SNELL_UNIT"
    if command -v systemctl >/dev/null; then
        systemctl "$2" "$unit" 2>/dev/null
    elif command -v rc-service >/dev/null; then
        rc-service "$unit" "$2" 2>/dev/null
    fi
}

open_ports() {
    if command -v ufw >/dev/null && ufw status 2>/dev/null | grep -q "Status: active"; then
        ufw allow "$REALITY_PORT/tcp" >/dev/null 2>&1 || true
        ufw allow "$HY2_PORT/udp" >/dev/null 2>&1 || true
        ufw allow "$ANYTLS_PORT/tcp" >/dev/null 2>&1 || true
        ufw allow "$TUIC_PORT/udp" >/dev/null 2>&1 || true
        ufw allow "$SS_PORT" >/dev/null 2>&1 || true
        ufw allow "$SNELL_PORT/tcp" >/dev/null 2>&1 || true
    elif command -v firewall-cmd >/dev/null && firewall-cmd --state >/dev/null 2>&1; then
        for p in "$REALITY_PORT/tcp" "$HY2_PORT/udp" "$ANYTLS_PORT/tcp" "$TUIC_PORT/udp" "$SS_PORT/tcp" "$SS_PORT/udp" "$SNELL_PORT/tcp"; do
            firewall-cmd --permanent --add-port="$p" >/dev/null 2>&1 || true
        done
        firewall-cmd --reload >/dev/null 2>&1 || true
    fi
}

enable_bbr() {
    if [[ "$(sysctl -n net.ipv4.tcp_congestion_control 2>/dev/null)" == "bbr" ]]; then
        info "BBR 已开启"
        return 0
    fi
    if ! sysctl net.ipv4.tcp_available_congestion_control 2>/dev/null | grep -qw bbr; then
        warn "当前内核不支持 BBR"
        return 1
    fi
    mkdir -p /etc/sysctl.d
    cat > /etc/sysctl.d/99-chuxue-bbr.conf <<'EOF'
net.core.default_qdisc=fq
net.ipv4.tcp_congestion_control=bbr
EOF
    sysctl -p /etc/sysctl.d/99-chuxue-bbr.conf >/dev/null 2>&1 || sysctl --system >/dev/null 2>&1 || true
    if [[ "$(sysctl -n net.ipv4.tcp_congestion_control 2>/dev/null)" == "bbr" ]]; then
        info "已开启 BBR"
    else
        warn "BBR 设置已写入 /etc/sysctl.d/99-chuxue-bbr.conf, 重启后生效"
    fi
}

bbr_menu() {
    title "BBR 加速"
    local cur qd
    cur="$(sysctl -n net.ipv4.tcp_congestion_control 2>/dev/null || echo unknown)"
    qd="$(sysctl -n net.core.default_qdisc 2>/dev/null || echo unknown)"
    echo "当前拥塞控制: $cur   队列调度: $qd"
    if [[ "$cur" == "bbr" ]]; then
        info "BBR 已开启, 无需操作"
    else
        local a=""
        read -rp "BBR 未开启, 现在开启? [y/N]: " a || a=""
        [[ "$a" == "y" || "$a" == "Y" ]] && enable_bbr
    fi
    read -rp "按回车返回菜单" _ || true
}

# ---------- 节点链接 ----------
links_for_host() {
    local host="$1" family="$2"
    local display_host="$host"
    [[ "$family" == "6" ]] && display_host="[$host]"
    # 链接输出排序: SS 第一, VLESS 第二, Snell 第三, 其余随意
    if proto_on ss; then
        local ss_userinfo
        ss_userinfo="$(printf '2022-blake3-aes-256-gcm:%s' "$SS_PASSWORD" | base64 -w0 2>/dev/null || printf '2022-blake3-aes-256-gcm:%s' "$SS_PASSWORD" | base64)"
        echo "ss://${ss_userinfo}@${display_host}:${SS_PORT}#${NODE_NAME}-SS2022-IPv${family}"
    fi
    if proto_on vless; then
        echo "vless://${UUID}@${display_host}:${REALITY_PORT}?encryption=none&flow=xtls-rprx-vision&security=reality&sni=${REALITY_SNI}&fp=chrome&pbk=${REALITY_PUBLIC_KEY}&sid=${REALITY_SHORT_ID}&support-x25519mlkem768=true&type=tcp#${NODE_NAME}-Reality-IPv${family}"
    fi
    if proto_on snell; then
        echo "--- Surge 格式 (Snell v6) ---"
        echo "${NODE_NAME}-Snellv6-IPv${family} = snell, ${host}, ${SNELL_PORT}, psk=${SNELL_PSK}, version=6, reuse=true, tfo=true"
    fi
    if proto_on hy2; then
        echo "hysteria2://${HY2_PASSWORD}@${display_host}:${HY2_PORT}?insecure=1&sni=chuxue-node#${NODE_NAME}-HY2-IPv${family}"
    fi
    if proto_on anytls; then
        echo "anytls://${ANYTLS_PASSWORD}@${display_host}:${ANYTLS_PORT}?insecure=1#${NODE_NAME}-AnyTLS-IPv${family}"
    fi
    if proto_on tuic; then
        echo "tuic://${UUID}:${TUIC_PASSWORD}@${display_host}:${TUIC_PORT}?congestion_control=bbr&alpn=h3&allow_insecure=1#${NODE_NAME}-TUIC-IPv${family}"
    fi
}

show_links() {
    load_state
    detect_ips
    title "节点链接 (IPv4 开关: $IPV4_ENABLED / IPv6 开关: $IPV6_ENABLED / 偏好: $(effective_preference))"
    if [[ $IPV4_ENABLED -eq 1 && -n "$PUBLIC_IPV4" ]]; then
        echo "--- IPv4 ($PUBLIC_IPV4) ---"
        links_for_host "$PUBLIC_IPV4" "4"
    fi
    if [[ $IPV6_ENABLED -eq 1 && -n "$PUBLIC_IPV6" ]]; then
        echo "--- IPv6 ($PUBLIC_IPV6) ---"
        links_for_host "$PUBLIC_IPV6" "6"
    fi
}

show_status() {
    load_state
    echo "初雪节点 v$CX_VERSION"
    echo "IPv4 开关: $IPV4_ENABLED   IPv6 开关: $IPV6_ENABLED"
    echo "偏好设置: $IP_PREFERENCE   实际生效: $(effective_preference)"
    echo "Xray 出站策略: $(xray_domain_strategy)   sing-box 策略: $(singbox_strategy | sed 's/^$/(空=双栈默认)/')"
    echo "监听地址: $(listen_addr)"
    echo "WARP 模式: $WARP_MODE${WARP_ADDRESS_V4:+   WARP 出口: $WARP_ADDRESS_V4}"
    echo "BBR: $(sysctl -n net.ipv4.tcp_congestion_control 2>/dev/null || echo unknown)"
    echo "端口: Reality=$REALITY_PORT HY2=$HY2_PORT AnyTLS=$ANYTLS_PORT TUIC=$TUIC_PORT SS2022=$SS_PORT Snell=$SNELL_PORT"
    svc xray status >/dev/null 2>&1 && echo "cx-xray: 运行中" || echo "cx-xray: 未运行"
    svc singbox status >/dev/null 2>&1 && echo "cx-singbox: 运行中" || echo "cx-singbox: 未运行"
    svc snell status >/dev/null 2>&1 && echo "cx-snell: 运行中" || echo "cx-snell: 未运行"
}

# ---------- IP 开关与偏好 ----------
apply_ip_settings() {
    save_state
    gen_xray_config
    gen_singbox_config
    gen_snell_config
    svc xray restart || true
    svc singbox restart || true
    svc snell restart || true
    info "已生效: IPv4=$IPV4_ENABLED IPv6=$IPV6_ENABLED 偏好=$(effective_preference) (Xray: $(xray_domain_strategy) / sing-box: $(singbox_strategy))"
}

ip_settings_menu() {
    while true; do
        title "IPv4 / IPv6 设置"
        echo "当前: IPv4 开关=$IPV4_ENABLED  IPv6 开关=$IPV6_ENABLED  偏好=$IP_PREFERENCE (实际: $(effective_preference))"
        echo " 1) 开/关 IPv4"
        echo " 2) 开/关 IPv6"
        echo " 3) 偏好: 双栈 (IPV4/IPV6 同时开启)"
        echo " 4) 偏好: IPV4优先"
        echo " 5) 偏好: IPV6优先"
        echo " 6) 偏好: 仅IPV4"
        echo " 7) 偏好: 仅IPV6"
        echo " 0) 返回"
        read -rp "选择: " ch
        case "$ch" in
            1) IPV4_ENABLED=$((1 - IPV4_ENABLED)) ;;
            2) IPV6_ENABLED=$((1 - IPV6_ENABLED)) ;;
            3) IP_PREFERENCE="dual" ;;
            4) IP_PREFERENCE="ipv4" ;;
            5) IP_PREFERENCE="ipv6" ;;
            6) IP_PREFERENCE="ipv4only" ;;
            7) IP_PREFERENCE="ipv6only" ;;
            0) return ;;
            *) warn "无效选择"; continue ;;
        esac
        if [[ $IPV4_ENABLED -eq 0 && $IPV6_ENABLED -eq 0 ]]; then
            warn "IPv4/IPv6 不能同时关闭, 已回滚"; load_state; continue
        fi
        detect_ips
        apply_ip_settings
    done
}

# ---------- 安装 / 卸载 ----------
do_install() {
    need_root
    # state 已在入口/菜单加载, 命令行开关也已覆盖, 这里不再 load_state,
    # 否则 --protocols/--prefer 的值会被 state 文件旧值冲掉。
    mkdir -p "$CX_DIR" && chmod 700 "$CX_DIR"
    ensure_deps
    detect_ips
    prompt_install_config
    proto_on vless && install_xray
    singbox_needed && install_singbox
    proto_on snell && { install_snell || true; }
    gen_credentials
    ensure_warp_account || true
    gen_cert
    proto_on vless && gen_xray_config
    singbox_needed && gen_singbox_config
    proto_on snell && gen_snell_config
    if proto_on vless; then
        "$XRAY_BIN" run -test -c "$CX_XRAY_JSON" >/dev/null || { err "Xray 配置校验失败"; exit 1; }
    fi
    if singbox_needed; then
        "$SINGBOX_BIN" check -c "$CX_SINGBOX_JSON" >/dev/null || { err "sing-box 配置校验失败"; exit 1; }
    fi
    save_state
    ensure_shortcut
    write_services
    open_ports
    enable_bbr
    proto_on vless && svc xray restart
    singbox_needed && svc singbox restart
    proto_on snell && { svc snell restart || true; }
    info "安装完成"
    show_links
}

do_uninstall() {
    need_root
    read -rp "确认卸载初雪节点? 服务、配置和凭据都会删除 [y/N]: " ans
    [[ "$ans" == "y" || "$ans" == "Y" ]] || { echo "已取消"; return; }
    svc xray stop || true
    svc singbox stop || true
    svc snell stop || true
    if command -v systemctl >/dev/null; then
        systemctl disable "$XRAY_UNIT" "$SINGBOX_UNIT" "$SNELL_UNIT" >/dev/null 2>&1 || true
        rm -f "/etc/systemd/system/${XRAY_UNIT}.service" "/etc/systemd/system/${SINGBOX_UNIT}.service" "/etc/systemd/system/${SNELL_UNIT}.service"
        systemctl daemon-reload
    fi
    rm -rf "$CX_DIR"
    rm -f "$CX_SHORTCUT"
    info "已卸载 (Xray/sing-box 二进制保留在 /usr/local/bin, 可自行删除)"
}

# ---------- 菜单 ----------
menu() {
    need_root
    load_state
    while true; do
        title "初雪节点 v$CX_VERSION"
        echo " 1) 搭建节点"
        echo " 2) 查看节点链接"
        echo " 3) IPv4 / IPv6 设置 (开关 + 优先模式)"
        echo " 4) WARP 设置 (不启用 / 分流 / 全局)"
        echo " 5) 查看状态"
        echo " 6) 重启服务"
        echo " 7) IP质量测试"
        echo " 8) 三网回程路线/速度"
        echo " 9) BBR 加速 (查看 / 开启)"
        echo " 10) 卸载"
        echo " 0) 退出"
        read -rp "选择: " ch
        case "$ch" in
            1) install_wizard; do_install ;;
            2) show_links ;;
            3) ip_settings_menu ;;
            4) warp_menu ;;
            5) show_status ;;
            6) svc xray restart; svc singbox restart; svc snell restart || true; info "已重启" ;;
            7) run_ip_quality ;;
            8) network_test_menu ;;
            9) bbr_menu ;;
            10) do_uninstall ;;
            0) exit 0 ;;
            *) warn "无效选择" ;;
        esac
    done
}

# ---------- 命令行 ----------
usage() {
    cat <<EOF
初雪节点 v$CX_VERSION
用法: $0 [选项]
  (无参数)               打开菜单
  --install              安装/重新部署
  --links                显示节点链接
  --status               显示状态
  --uninstall            卸载
  --ipv4 on|off          IPv4 开关
  --ipv6 on|off          IPv6 开关
  --prefer MODE          dual|ipv4|ipv6|ipv4only|ipv6only
                         dual=双栈默认 ipv4=优先IPv4 ipv6=优先IPv6
                         ipv4only=仅IPv4出站 ipv6only=仅IPv6出站
  --protocols LIST       启用的协议, 逗号分隔: vless,hy2,anytls,tuic,ss,snell
                         例如只搭 VLESS+Snell: --protocols vless,snell
  --name NAME            节点名称 (链接里显示的名字), 默认 初雪
                         全新安装时也会交互询问名称和各协议端口,
                         端口直接回车 = 随机高位端口 (20000-60000)
  --warp MODE            WARP 出站: off|split|global
                         split=仅 AI/流媒体域名走 WARP, global=全部流量走 WARP
  开关类参数可组合, 改完自动重写配置并重启, 例如:
    $0 --ipv6 off --prefer ipv4
EOF
}

main() {
    if [[ $# -eq 0 ]]; then menu; return; fi
    local changed=0
    while [[ $# -gt 0 ]]; do
        case "$1" in
            --install)   do_install; return ;;
            --links)     show_links; return ;;
            --status)    show_status; return ;;
            --uninstall) do_uninstall; return ;;
            --help|-h)   usage; return ;;
            --ipv4) IPV4_ENABLED=$([[ "$2" == "on" ]] && echo 1 || echo 0); changed=1; shift 2 ;;
            --ipv6) IPV6_ENABLED=$([[ "$2" == "on" ]] && echo 1 || echo 0); changed=1; shift 2 ;;
            --prefer)
                case "$2" in
                    dual|ipv4|ipv6|ipv4only|ipv6only) IP_PREFERENCE="$2" ;;
                    *) err "无效的偏好模式: $2"; usage; exit 1 ;;
                esac
                changed=1; shift 2 ;;
            --protocols) CX_PROTOCOLS="$2"; changed=1; shift 2 ;;
            --name) NODE_NAME="$(sanitize_name "$2")"; [[ -z "$NODE_NAME" ]] && NODE_NAME="初雪"; changed=1; shift 2 ;;
            --warp)
                case "$2" in
                    off|split|global) WARP_MODE="$2" ;;
                    *) err "无效的 WARP 模式: $2"; usage; exit 1 ;;
                esac
                changed=1; shift 2 ;;
            *) err "未知参数: $1"; usage; exit 1 ;;
        esac
    done
    if [[ $changed -eq 1 ]]; then
        need_root
        load_state_after_args "$@"
        if [[ $IPV4_ENABLED -eq 0 && $IPV6_ENABLED -eq 0 ]]; then
            err "IPv4/IPv6 不能同时关闭"; exit 1
        fi
        if warp_on; then ensure_warp_account || true; fi
        if warp_on && [[ -z "$WARP_PRIVATE_KEY" ]]; then
            err "WARP 账号未就绪, 已取消本次修改"; exit 1
        fi
        detect_ips
        apply_ip_settings
    fi
}

# 命令行改开关时: 先读旧 state, 再用命令行值覆盖 (上面的解析发生在
# load_state 之前, 这里把两者合并 — 解析时保存的值暂存在变量里)。
load_state_after_args() { :; }

# 当脚本被 source 时只加载函数, 不执行 main (便于本地测试纯函数)。
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    # 命令行开关需要在 load_state 前解析: 先备份参数里的开关值
    _args=("$@")
    load_state
    # 重新应用命令行开关 (覆盖 state 里的旧值)
    _i=0
    while [[ $_i -lt ${#_args[@]} ]]; do
        case "${_args[$_i]}" in
            --ipv4) IPV4_ENABLED=$([[ "${_args[$((_i+1))]}" == "on" ]] && echo 1 || echo 0); _i=$((_i+2)) ;;
            --ipv6) IPV6_ENABLED=$([[ "${_args[$((_i+1))]}" == "on" ]] && echo 1 || echo 0); _i=$((_i+2)) ;;
            --prefer) IP_PREFERENCE="${_args[$((_i+1))]}"; _i=$((_i+2)) ;;
            --protocols) CX_PROTOCOLS="${_args[$((_i+1))]}"; _i=$((_i+2)) ;;
            --name) _nm="$(sanitize_name "${_args[$((_i+1))]}")"; [[ -n "$_nm" ]] && NODE_NAME="$_nm"; _i=$((_i+2)) ;;
            --warp) WARP_MODE="${_args[$((_i+1))]}"; _i=$((_i+2)) ;;
            *) _i=$((_i+1)) ;;
        esac
    done
    main "${_args[@]}"
fi
