#!/bin/bash

_install() {

UCLOUD_CMDBAPI_SERVICE=api-gw.ucloudadmin.com
sn=`dmidecode -s system-serial-number |grep -v ^#  | sed s/[[:space:]]//g`
cmdb_info=`curl -s -H 'api-key: b58cc3fb78344ad0a3710dc05813b112' "http://$UCLOUD_CMDBAPI_SERVICE/cmdb/v2/ci/search?category=Server&q=SN=='$sn'&fields=(Manufacture,MachineType)"`
Manufacturer=`echo $cmdb_info |jq .| grep Manufacture|awk -F '"' '{print $4}'`
MachineType=`echo $cmdb_info |jq .| grep MachineType|awk -F '"' '{print $4}'`
if [[ -z $MachineType ]]; then
    MachineType=`dmidecode -t3 | grep Version | awk '{print $NF}'`
fi
if [[ -z $Manufacturer ]]; then
    Manufacturer=`dmidecode -t1 | grep Manufacturer | awk '{print $NF}'`
fi

# 获取配置中心网卡排序规则 ##注意此处## remote_nic_info 为空格分割的字符串不是数组
#    remote_nic_info=`curl -s http://uconf.service.ucloud.cn:8080/configfiles/json/1/usa-init/uops.nicorder | jq -r ".[\"${MachineType}.${Manufacturer}\"]"`
# remote_nic_info="eth0:X710:10G eth1:X710:10G eth2:MT2892:0016 eth3:MT2892:0016 eth4:MT2892:0018 eth5:MT2892:0018 eth6:MT2892:0018 eth7:MT2892:0018"
    remote_nic_info=`/usr/bin/python $BASEDIR/utils/GetApolloConf.py nicorder "${MachineType}.${Manufacturer}"`

    if [[ -z $remote_nic_info || $(echo "$remote_nic_info" | wc -l) -gt 1 ]];then
        PRINT_ERR "[ERROR] $0 get nicorder error from uconf"
    fi

#    PATH=$INIT_TMP_DIR/bin:$PATH
    if ip l show bond0 | grep -q UP ;then
        ifdown bond0
        BONDDOWN_FLAG=1
    fi

    index=0
    nic_name=()
    nic_name_origin=()
    nic_slot=()
    nic_mac=()
    nic_speed=()
    nic_pci_name=()
    for local_nic in $(ls /sys/class/net/ | grep -vE "lo|bond|tmfifo|usb|idrac|vnet");
    do
        # vf会影响排序,要continue掉
        tmp_slot=$(ethtool -i $local_nic|grep bus-info|awk '{print $NF}')
        if [[ -z $tmp_slot || $tmp_slot = "bus-info:" ]];then
            continue
        fi
        if lspci -D -s "$tmp_slot" | grep -q "Virtual Function";then
            continue
        fi
        nic_name[$index]="eth$index"
        nic_name_origin[$index]=$local_nic
        bus_info=$(ethtool -i "$local_nic" |grep bus-info|awk '{print $NF}')
        nic_slot[$index]=$bus_info
        nic_mac[$index]=$(cat /sys/class/net/$local_nic/address)
        nic_speed[$index]=$(ethtool $local_nic | grep 'base' | tail -1 | sed -n 's#.*\s\([0-9]*\)base.*#\1#p')
        nic_pci_name[$index]=$(lspci -Dnnmb -s $bus_info)
        index=$((index+1))
    done

    if [[ $BONDDOWN_FLAG == 1 ]];then
        ifup bond0
    fi

# 首先 根据 BusID/SlotID 的从小到大排序 🫧冒泡排序
    for i in "${!nic_name[@]}"
    do
        for j in $(seq $((i+1)) $((${#nic_name[@]}-1)))
        do
            dev_num=$((16#$(echo ${nic_slot[$j]}|sed -e 's/[:\.]//g')))
            dev_num_pre=$((16#$(echo ${nic_slot[$i]}|sed -e 's/[:\.]//g')))
            if [[ $dev_num -gt $dev_num_pre ]];then
                continue
            fi
            nic_name_origin_tmp=${nic_name_origin[$i]}
            nic_slot_tmp=${nic_slot[$i]}
            nic_mac_tmp=${nic_mac[$i]}
            nic_speed_tmp=${nic_speed[$i]}
            nic_pci_name_tmp=${nic_pci_name[$i]}

            nic_name_origin[$i]=${nic_name_origin[$j]}
            nic_slot[$i]=${nic_slot[$j]}
            nic_mac[$i]=${nic_mac[$j]}
            nic_speed[$i]=${nic_speed[$j]}
            nic_pci_name[$i]=${nic_pci_name[$j]}

            nic_name_origin[$j]=${nic_name_origin_tmp}
            nic_slot[$j]=${nic_slot_tmp}
            nic_mac[$j]=${nic_mac_tmp}
            nic_speed[$j]=${nic_speed_tmp}
            nic_pci_name[$j]=${nic_pci_name_tmp}
        done
    done

# 其次 根据 uconf 中的配置排序
    ready_nic=''
    for nicinfo in $remote_nic_info
    do
        uconf_nic_name=$(echo $nicinfo|awk -F ":" '{print $1}')
        uconf_nic_model=$(echo $nicinfo|awk -F ":" '{print $2}')
        uconf_nic_speed=$(echo $nicinfo|awk -F ":" '{print $3}')
        uconf_index=${uconf_nic_name:3}
        for i in "${!nic_name[@]}"
        do
            if [[ $ready_nic =~ eth$i ]];then
                continue
            fi
            if [[ ${nic_pci_name[$i]} =~ $uconf_nic_model && ${nic_pci_name[$i]} =~ $uconf_nic_speed ]];then
                if [[ $uconf_index -ne $i ]];then
                    nic_name_origin_tmp=${nic_name_origin[$uconf_index]}
                    nic_slot_tmp=${nic_slot[$uconf_index]}
                    nic_mac_tmp=${nic_mac[$uconf_index]}
                    nic_speed_tmp=${nic_speed[$uconf_index]}
                    nic_pci_name_tmp=${nic_pci_name[$uconf_index]}

                    nic_name[$uconf_index]=$uconf_nic_name
                    nic_name_origin[$uconf_index]=${nic_name_origin[$i]}
                    nic_slot[$uconf_index]=${nic_slot[$i]}
                    nic_mac[$uconf_index]=${nic_mac[$i]}
                    nic_speed[$uconf_index]=${nic_speed[$i]}
                    nic_pci_name[$uconf_index]=${nic_pci_name[$i]}

                    nic_name_origin[$i]=${nic_name_origin_tmp}
                    nic_slot[$i]=${nic_slot_tmp}
                    nic_mac[$i]=${nic_mac_tmp}
                    nic_speed[$i]=${nic_speed_tmp}
                    nic_pci_name[$i]=${nic_pci_name_tmp}
                fi
                ready_nic+="$uconf_nic_name"
                break
            fi
        done
    done

    
    rule_file="/tmp/os_init/70-persistent-net.rules"
    cat  > $rule_file <<EOF
# This file was automatically generated by the $0
# program, run by the persistent-net-generator.rules rules file."
#
# You can modify it, as long as you keep each rule on a single
# line, and change only the value of the NAME= key.

EOF
    udev_head="# PCI device"

    for i in "${!nic_name[@]}"
    do
        if [[ -z ${nic_mac[$i]} ]];then
            continue
        fi
        nic=${nic_name[$i]}
        if [[ $OS != CentOS6 ]];then
            nic=${nic/eth/net}
        fi
        cat >> $rule_file <<EOF
${udev_head} ${nic_pci_name[$i]}
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="${nic_mac[$i]}", ATTR{type}=="1", KERNEL=="eth*", NAME="$nic"

EOF
    done
    true_rule_file="/etc/udev/rules.d/70-persistent-net.rules"
    if ! diff $true_rule_file $rule_file ;then
        PRINT_INFO "[INFO] 重新进行网卡排序"
        \cp $true_rule_file /tmp/os_init/70-persistent-net.rules.bak
        install $rule_file $true_rule_file
        # 检测网卡配置是否跟 udev 一致
        source $(grep GATEWAY= /etc/sysconfig/network-scripts/ifcfg* |awk -F ":" '{print $1}')
        if [[ $DEVICE == bond* ]];then
            DEVICE=net2
        fi
        net_mac=$(grep $DEVICE /etc/udev/rules.d/70-persistent-net.rules |grep -oP '([0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5})' )
        for i in /sys/class/net/net*
        do
            mac=$(cat $i/address)
            if [[ $net_mac == $mac ]];then
                if ! cat $i/carrier |grep -q 1 
                then
                    PRINT_ERR "[ERROR] $DEVICE not $i 接线异常,重启后可能无网络, 请检查ifcfg-*配置"
                    return 1
                fi
            fi
        done
    fi
}

_check() {
    _check="PASS"
}

