#!/bin/bash

# 检测系统版本
OS_VERSION=$(awk -F= '/^NAME/{print $2}' /etc/os-release)
echo "当前系统版本: $OS_VERSION"

# 根据系统选择对应的网络配置方式
if [[ $OS_VERSION == *"Ubuntu"* ]]; then
    CONFIG_DIR="/etc/netplan"
elif [[ $OS_VERSION == *"CentOS"* ]]; then
    CONFIG_DIR="/etc/sysconfig/network-scripts"
else
    echo "不支持的系统版本"
    exit 1
fi

# 检测所有检测到的网卡，并列出显示网卡名称
echo "检测到的网卡:"
ip link show | grep -oP '(?<=en)\w+' | sort -u
echo "请通过123的方式选择需要编辑的网卡: "
read -p "网卡名称: " NIC

# 询问用户是否需要配置单网卡多IP还是当前网卡只配置一个IP
echo "1. 配置单网卡多IP"
echo "2. 当前网卡只配置一个IP"
read -p "请选择(1/2): " IP_MODE

# 配置网络设置
CONFIG_FILE="${CONFIG_DIR}/01-netcfg.yaml"
echo "network:" > $CONFIG_FILE
echo "  version: 2" >> $CONFIG_FILE
echo "  renderer: networkd" >> $CONFIG_FILE
echo "  ethernets:" >> $CONFIG_FILE
echo "    $NIC:" >> $CONFIG_FILE
echo "      dhcp4: no" >> $CONFIG_FILE

if [[ $IP_MODE == "1" ]]; then
    # 单网卡多IP配置
    read -p "请输入第一个IP地址: " IP1
    read -p "请输入子网掩码: " SUBNET1
    read -p "请输入网关: " GATEWAY1
    echo "        - $IP1/$SUBNET1" >> $CONFIG_FILE
    echo "      gateway4: $GATEWAY1" >> $CONFIG_FILE
    
    while true; do
        read -p "是否需要添加更多IP? (y/n): " ADD_MORE
        if [[ "$ADD_MORE" == "y" || "$ADD_MORE" == "Y" ]]; then
            read -p "请输入IP地址: " EXTRA_IP
            read -p "请输入子网掩码: " EXTRA_SUBNET
            read -p "请输入网关: " EXTRA_GATEWAY
            echo "        - $EXTRA_IP/$EXTRA_SUBNET" >> $CONFIG_FILE
            # 为额外的IP地址添加路由
            echo "routes:" >> $CONFIG_FILE
            echo "  - to: 0.0.0.0/0" >> $CONFIG_FILE
            echo "    via: $EXTRA_GATEWAY" >> $CONFIG_FILE
            echo "    on: $NIC" >> $CONFIG_FILE
        else
            break
        fi
    done
else
    # 单IP配置
    read -p "请输入IP地址: " IP
    read -p "请输入子网掩码: " SUBNET
    read -p "请输入网关: " GATEWAY
    echo "        - $IP/$SUBNET" >> $CONFIG_FILE
    echo "      gateway4: $GATEWAY" >> $CONFIG_FILE
fi

read -p "请输入DNS: " DNS
echo "      nameservers:" >> $CONFIG_FILE
echo "        addresses: [$DNS]" >> $CONFIG_FILE

# 询问是否需要配置永久静态路由
read -p "是否需要配置永久静态路由? (1/2): " ROUTE_MODE

if [[ $ROUTE_MODE == "1" ]]; then
    read -p "请输入目的网络: " DEST_NETWORK
    read -p "请输入子网掩码: " DEST_SUBNET
    read -p "请输入下一跳地址: " NEXT_HOP
    echo "配置静态路由..."
    echo "routes:" >> $CONFIG_FILE
    echo "  - to: $DEST_NETWORK/$DEST_SUBNET" >> $CONFIG_FILE
    echo "    via: $NEXT_HOP" >> $CONFIG_FILE
fi

# 应用配置并验证
if [[ $OS_VERSION == *"Ubuntu"* ]]; then
    sudo netplan apply
elif [[ $OS_VERSION == *"CentOS"* ]]; then
    sudo systemctl restart network
fi

# 输出配置信息
cat $CONFIG_FILE

# 验证配置
echo "验证配置..."
ip addr show $NIC
ip route show

echo "配置完成!"