#!/bin/bash

hostname=$1

if [ -z ${hostname} ];then
        echo "Parameter required: hostname"
        exit
fi

rm -f /tmp/ip_info
if curl -o /tmp/ip_info https://dl.erdaye.shop/network/${hostname} > /dev/null ;then
        sleep 1
else
        echo "Host not found"
        exit
fi

cidr_info(){
        if [ $1 -eq 24 ];then
                echo "255.255.255.0 253"
        elif [ $1 -eq 25 ];then
                echo "255.255.255.128 125"
        elif [ $1 -eq 26 ];then
                echo "255.255.255.192 61"
        elif [ $1 -eq 27 ];then
                echo "255.255.255.224 29"
        elif [ $1 -eq 28 ];then
                echo "255.255.255.240 13"
        elif [ $1 -eq 29 ];then
                echo "255.255.255.248 5"
        fi
}

list_all_ip(){
        if grep "dufu" /tmp/ip_info > null 2>&1;then
                for ip_info in $(cat /tmp/ip_info | grep -v "#");do
                        ip=$(echo ${ip_info} | awk -F"/" '{print$1}')
                        cidr=$(echo ${ip_info} | awk -F"/" '{print$2}')
                        netmask=$(cidr_info ${cidr} | awk '{print$1}')
                        ip_list+=(${ip})
                        cidr_list+=(${cidr})
                        netmask_list+=(${netmask})
                done
        else
                for ip_info in $(cat /tmp/ip_info | grep -v "#");do
                        net_c3=$(echo ${ip_info} | awk -F[./] '{print$1"."$2"."$3}')
                        let net_c4=$(echo ${ip_info} | awk -F[./] '{print$4}')+2
                        cidr=$(echo ${ip_info} | awk -F[./] '{print$5}')
                        netmask=$(cidr_info ${cidr} | awk '{print$1}')
                        ip_num=$(cidr_info ${cidr} | awk '{print$2}')
                        for id in $(seq 1 ${ip_num});do
                                ip_list+=(${net_c3}.${net_c4})
                                cidr_list+=(${cidr})
                                netmask_list+=(${netmask})
                                let net_c4=${net_c4}+1
                        done
                done
        fi
}

ensure_resolv_conf(){
        # 仅在被 NetworkManager 生成且未写入 DNS 时追加，避免覆盖用户配置
        if grep -q "Generated by NetworkManager" /etc/resolv.conf; then
                if ! grep -q "nameserver 8.8.8.8" /etc/resolv.conf; then
                        {
                                echo "nameserver 8.8.8.8"
                                echo "nameserver 114.114.114.114"
                        } >> /etc/resolv.conf
                fi
        fi
}

nmcli_manage(){
        network_nic=$(ip route show | awk '/default/{print$5}')

        # 仅根据默认路由对应的网卡生成/选择连接，避免误用其他接口
        connection_name=$(nmcli -t -f NAME,DEVICE connection show --active | awk -F: -v dev="${network_nic}" '$2==dev{print $1; exit}')
        if [ -z "${connection_name}" ]; then
                connection_name=${network_nic}
                echo "未找到该网卡的激活连接，创建并启用 ${connection_name}"
                nmcli connection add type ethernet ifname "${network_nic}" con-name "${connection_name}" autoconnect yes > /dev/null 2>&1
        else
                echo "使用激活连接: ${connection_name}"
        fi

        # 将同网卡的旧连接停用、禁用自启动并追加 _old 后缀，避免残留冲突
        for old_conn in $(nmcli -t -f NAME,DEVICE connection show | awk -F: -v dev="${network_nic}" -v keep="${connection_name}" '$2==dev && $1!=keep{print $1}'); do
                nmcli connection down "${old_conn}" > /dev/null 2>&1
                nmcli connection modify "${old_conn}" autoconnect no
                if [[ "${old_conn}" != *_old ]]; then
                        nmcli connection modify "${old_conn}" connection.id "${old_conn}_old" > /dev/null 2>&1
                fi
        done

        # 如修改失败（文件缺失等）则备份旧连接并创建新连接
        if ! nmcli connection modify "${connection_name}" ipv4.dns "" ipv4.gateway "" ipv4.addresses "" ipv4.method disabled ipv6.method link-local; then
                echo "连接 ${connection_name} 修改失败，备份并重建"
                nmcli connection down "${connection_name}" > /dev/null 2>&1
                nmcli connection modify "${connection_name}" autoconnect no > /dev/null 2>&1
                if [[ "${connection_name}" != *_old ]]; then
                        nmcli connection modify "${connection_name}" connection.id "${connection_name}_old" > /dev/null 2>&1
                fi
                connection_name=${network_nic}
                nmcli connection add type ethernet ifname "${network_nic}" con-name "${connection_name}" autoconnect yes > /dev/null 2>&1
                nmcli connection modify "${connection_name}" ipv4.dns "" ipv4.gateway "" ipv4.addresses "" ipv4.method disabled ipv6.method link-local
        fi

        # 清空后重新写入地址/网关/DNS
        list_all_ip
        for len in $(seq 1 ${#ip_list[@]});do
                let id=${len}-1
                ip=$(echo ${ip_list[$id]})
                cidr=$(echo ${cidr_list[$id]})
                netmask=$(echo ${netmask_list[$id]})
                nmcli connection modify "${connection_name}" +ipv4.addresses ${ip}/${cidr} ipv4.method manual ipv6.method link-local
        done
        gateway=$(awk '/gateway/{print$2}' /tmp/ip_info)
        nmcli connection modify "${connection_name}" ipv4.gateway ${gateway}
        nmcli connection modify "${connection_name}" ipv4.dns "8.8.8.8"
        nmcli connection modify "${connection_name}" ipv4.ignore-auto-dns yes
        nmcli connection up "${connection_name}"
        ensure_resolv_conf
}

ifcfg(){
        network_nic=$(ip route show | awk '/default/{print$5}')
        mac=$(ip link show dev ${network_nic} | awk '/ether/{print$2}')
        gateway=$(awk '/gateway/{print$2}' /tmp/ip_info)
        echo -n > /etc/sysconfig/network-scripts/ifcfg-${network_nic}
        cat >> /etc/sysconfig/network-scripts/ifcfg-${network_nic} <<INTERFACE
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=static
HWADDR=${mac}
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=no
NAME=${network_nic}
DEVICE=${network_nic}
ONBOOT=yes
INTERFACE
        list_all_ip
        for len in $(seq 1 ${#ip_list[@]});do
                let id=${len}-1
                ip=$(echo ${ip_list[$id]})
                cidr=$(echo ${cidr_list[$id]})
                netmask=$(echo ${netmask_list[$id]})
                if [ ${id} -eq 0 ];then
                        cat >> /etc/sysconfig/network-scripts/ifcfg-${network_nic} <<INTERFACE
IPADDR=${ip}
NETMASK=${netmask}
GATEWAY=${gateway}
DNS1=8.8.8.8
INTERFACE
                else
                        cat >> /etc/sysconfig/network-scripts/ifcfg-${network_nic} <<INTERFACE
IPADDR${id}=${ip}
NETMASK${id}=${netmask}
INTERFACE
        echo "nameserver 8.8.8.8" > /etc/resolv.conf
                fi
        done
}

netcfg(){
        net_conf_file=$(ls /etc/netplan/*.yaml)
        network_nic=$(ip route show | awk '/default/{print$5}')
        echo -n > ${net_conf_file}
        cat > ${net_conf_file} <<INTERFACE
network:
  version: 2
  renderer: networkd
  ethernets:
    ${network_nic}:
      addresses:
INTERFACE
        list_all_ip
        for len in $(seq 1 ${#ip_list[@]});do
                let id=${len}-1
                ip=$(echo ${ip_list[$id]})
                cidr=$(echo ${cidr_list[$id]})
                netmask=$(echo ${netmask_list[$id]})
                        echo "        - ${ip}/${cidr}" >> ${net_conf_file}
        done
        gateway=$(awk '/gateway/{print$2}' /tmp/ip_info)
        cat >> ${net_conf_file} <<INTERFACE
      gateway4: ${gateway}
      nameservers:
        addresses:
          - 8.8.8.8
          - 114.114.114.114
INTERFACE
        echo "nameserver 8.8.8.8" > /etc/resolv.conf
}

interface(){
        gateway=$(awk '/gateway/{print$2}' /tmp/ip_info)
        network_nic=$(ip route show | awk '/default/{print$5}')
        echo -n > /etc/network/interfaces
        list_all_ip
        for len in $(seq 1 ${#ip_list[@]});do
                let id=${len}-1
                ip=$(echo ${ip_list[$id]})
                cidr=$(echo ${cidr_list[$id]})
                netmask=$(echo ${netmask_list[$id]})
                if [ ${id} -eq 0 ];then
                        cat >> /etc/network/interfaces <<INTERFACE
auto ${network_nic}
iface ${network_nic} inet static
  address ${ip}
  netmask ${netmask}
  gateway ${gateway}
INTERFACE
                else
                        cat >> /etc/network/interfaces <<INTERFACE
auto ${network_nic}:${id}
iface ${network_nic}:${id} inet static
  address ${ip}
  netmask ${netmask}
INTERFACE
                fi
        done
        echo "nameserver 8.8.8.8" > /etc/resolv.conf
}


if `grep "CentOS Linux release 7" /etc/redhat-release > /dev/null 2>&1`; then
        echo "System: CentOS 7"
        nmcli_manage
elif `grep "Rocky Linux release 9.4" /etc/redhat-release > /dev/null 2>&1`; then
        echo "System: Rocky Linux 9"
        nmcli_manage
elif `grep "CentOS Linux release 8" /etc/redhat-release > /dev/null 2>&1`; then
        echo "System: CentOS 8"
        ifcfg
elif `grep "CentOS Stream release 8" /etc/redhat-release > /dev/null 2>&1`; then
        echo "System: CentOS Stream 8"
        nmcli_manage
elif `grep "CentOS Stream release 9" /etc/redhat-release > /dev/null 2>&1`; then
        echo "System: CentOS Stream 9"
        nmcli_manage
elif `egrep "ubuntu1~14|Ubuntu 16" /proc/version > /dev/null 2>&1`; then
        echo "System: Ubuntu 14-16"
        interface
elif `egrep "Ubuntu 18|Ubuntu 20|Ubuntu 22|Ubuntu 24" /etc/issue > /dev/null 2>&1`; then
        echo "System: Ubuntu 18-24"
        netcfg
elif `egrep "Debian 8|Debian 10|Debian 12" /proc/version > /dev/null 2>&1`; then
        echo "System: Debian 10-12"
        interface
fi

