#!/bin/bash

# 备份原始的网络配置文件
backup_file="/etc/network/interfaces.bak_$(date +%F_%T)"
cp /etc/network/interfaces "$backup_file"
echo "已备份原始文件到: $backup_file"

# 读取网卡名称
interface=$(awk '/^iface/ && !/lo/ {print $2}' /etc/network/interfaces | head -n 1)
if [[ -z "$interface" ]]; then
    echo "无法从配置文件中提取网卡名称"
    exit 1
fi
echo "检测到的网卡: $interface"

# 读取 IP 地址
ip_address=$(awk '/address/ {print $2}' /etc/network/interfaces | head -n 1)
if [[ -z "$ip_address" ]]; then
    echo "无法从配置文件中提取IP地址"
    exit 1
fi
echo "检测到的IP地址: $ip_address"

# 读取网关
gateway=$(awk '/gateway/ {print $2}' /etc/network/interfaces | head -n 1)
if [[ -z "$gateway" ]]; then
    echo "无法从配置文件中提取网关"
    exit 1
fi
echo "检测到的网关: $gateway"

# 读取 DNS 服务器
dns_servers=$(awk '/dns-nameservers/ {$1=""; print $0}' /etc/network/interfaces | xargs)
if [[ -z "$dns_servers" ]]; then
    echo "无法从配置文件中提取DNS服务器"
    exit 1
fi
echo "检测到的DNS服务器: $dns_servers"

# 让用户交互输入桥接名称
read -p "请输入桥接接口名称 (如 br0): " bridge_name
if [[ -z "$bridge_name" ]]; then
    echo "桥接接口名称不能为空！"
    exit 1
fi

# 生成新的网络配置
cat > /etc/network/interfaces <<EOF
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

source /etc/network/interfaces.d/*

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto $interface
iface $interface inet manual

auto $bridge_name
iface $bridge_name inet static
    bridge_ports $interface
    address $ip_address
    gateway $gateway
    # dns-* options are implemented by the resolvconf package, if installed
    dns-nameservers $dns_servers
    bridge_stp off
    bridge_waitport 0
    bridge_fd 0
EOF

echo "新的网络配置已写入 /etc/network/interfaces"

# 配置 sysctl 参数
sysctl_config="/etc/sysctl.conf"
echo "正在写入 sysctl 配置..."

cat >> "$sysctl_config" <<EOF

# 自定义网络优化参数
net.ipv4.ip_forward = 1
net.netfilter.nf_conntrack_max = 999999999
net.nf_conntrack_max = 999999999
net.netfilter.nf_conntrack_buckets = 194857600
net.netfilter.nf_conntrack_icmp_timeout = 10
net.netfilter.nf_conntrack_tcp_timeout_syn_recv = 5
net.netfilter.nf_conntrack_tcp_timeout_syn_sent = 5
net.netfilter.nf_conntrack_tcp_timeout_established = 600
net.netfilter.nf_conntrack_tcp_timeout_fin_wait = 10
net.netfilter.nf_conntrack_tcp_timeout_time_wait = 10
net.netfilter.nf_conntrack_tcp_timeout_close_wait = 10
net.netfilter.nf_conntrack_tcp_timeout_last_ack = 10
EOF

# 应用 sysctl 配置
sysctl -p

echo "sysctl 参数已配置并应用"

# 重新启动网络服务
echo "正在重启网络服务..."
systemctl restart networking

echo "配置完成。"
