#!/bin/bash

enable_bbr() {
    echo "==> 启用 BBR..."

    if grep -q "net.core.default_qdisc=fq" /etc/sysctl.conf && grep -q "net.ipv4.tcp_congestion_control=bbr" /etc/sysctl.conf; then
        echo "BBR 已启用，无需重复设置。"
        return
    fi

    # 安装 ca-certificates
    if [ -f /etc/os-release ]; then
        source /etc/os-release
        case "$ID" in
            ubuntu|debian|armbian)
                apt-get update
                apt-get install -y ca-certificates
                ;;
            centos|almalinux|rocky|ol)
                yum -y update
                yum -y install ca-certificates
                ;;
            fedora|amzn|virtuozzo)
                dnf -y update
                dnf -y install ca-certificates
                ;;
            arch|manjaro)
                pacman -Sy --noconfirm ca-certificates
                ;;
            *)
                echo "不支持的系统：$ID，请手动安装 ca-certificates。"
                exit 1
                ;;
        esac
    fi

    # 设置内核参数
    echo "net.core.default_qdisc=fq" >> /etc/sysctl.conf
    echo "net.ipv4.tcp_congestion_control=bbr" >> /etc/sysctl.conf
    sysctl -p

    # 验证
    if [[ $(sysctl net.ipv4.tcp_congestion_control | awk '{print $3}') == "bbr" ]]; then
        echo "✅ BBR 已成功启用。"
    else
        echo "❌ 启用失败，请检查配置。"
    fi
}

disable_bbr() {
    echo "==> 关闭 BBR..."

    if ! grep -q "net.core.default_qdisc=fq" /etc/sysctl.conf || ! grep -q "net.ipv4.tcp_congestion_control=bbr" /etc/sysctl.conf; then
        echo "BBR 当前未启用。"
        return
    fi

    sed -i 's/net.core.default_qdisc=fq/net.core.default_qdisc=pfifo_fast/' /etc/sysctl.conf
    sed -i 's/net.ipv4.tcp_congestion_control=bbr/net.ipv4.tcp_congestion_control=cubic/' /etc/sysctl.conf
    sysctl -p

    if [[ $(sysctl net.ipv4.tcp_congestion_control | awk '{print $3}') == "cubic" ]]; then
        echo "✅ BBR 已成功关闭，切换为 CUBIC。"
    else
        echo "❌ 关闭失败，请检查配置。"
    fi
}

show_menu() {
    echo "=============================="
    echo " BBR 管理工具"
    echo "=============================="
    echo "1. 启用 BBR"
    echo "2. 关闭 BBR"
    echo "0. 退出"
    echo "=============================="
    read -rp "请输入选项 [0-2]: " input
    case "$input" in
        1) enable_bbr ;;
        2) disable_bbr ;;
        0) exit 0 ;;
        *) echo "❌ 无效选项";;
    esac
}

while true; do
    show_menu
done
