#!/usr/bin/env bash

# support:
# 1. BF 卡不组 bond 的机器
# 4. 400G RDMA for uhost: net2+udisk0, like uhost

source /ucloud/exports.ini
# VMFLAG: 1 true
# BFFLAG: 1 true
# BondIP
# HOSTIP

check_net_type() {
    if [[ $VMFLAG = 1 ]];then
        return 1
    elif [[ $BondIP ]];then
        return 1
    elif [[ $BFFLAG = 1 ]];then
        return 0
    # # 单独适配400G 单线 RoCE net2+udisk0
    # elif lspci -Dnnmb -d 0x15b3:1021:0200 &> /dev/null ;then
    #     extend_ifname=udisk0
    else
        return 1
    fi
}

_install() {
    return 0
}

_install_bf() {
    # 单线BF取消 本脚本留着给 沐曦 400G单线使用
    check_net_type || return 0
    PRINT_INFO VMFLAG: $VMFLAG BondIP: $BondIP BFFLAG: $BFFLAG
    PRINT_INFO BF NIC Grayscale
    extend_ifname=p0m0

    # request extend ip ,3线方案bond0 IP是预先分配好的，不用在这申请
    local ip_by_sn extend_ip_info extend_ip
    # source /ucloud/exports.ini
    JP='192.168.168.106'
    MAN_IP=`ip -o r get $JP|sed -n 's/.*src \([0-9.]*\) .*/\1/p'`
    if [[ -n $MAN_IP ]];then
        MAN_IP=$UCLOUD_IPADDR
    fi
    SN=$UCLOUD_SN
    ip_by_sn=$(curl -s -X GET -H 'Accept: application/json' -H 'api-key: f0ca152370904201a80de50ecae966fa' "http://api-gw.ucloudadmin.com/ipdb/intranet/ip?bind_resource=${SN}")
    if [[ `echo $ip_by_sn | jq -r '.data[]|.address'| wc -l` -gt 2 ]];then
        PRINT_ERR "[ERROR] SN 绑定的IP过多,请检查ipdb"
        return 1
    fi
    mapfile -t addr_array < <(jq -r '.data[]|.address' <<< $ip_by_sn)
    mapfile -t ipseg_array < <(jq -r '.data[]|.ipseg' <<< $ip_by_sn)

    for (( i = 0 ; i < ${#addr_array[@]} ; i++ ))
    do
        # echo $i
        # echo ${addr_array[$i]}
        # echo ${ipseg_array[$i]}
        if [[ ${addr_array[$i]} == "$MAN_IP" ]];then
            man_ipseg=${ipseg_array[$i]}
            break
        fi
    done

    # 打乱请求时间，防止IPDB重复IP
    sleep $((RANDOM%30))

    extend_ip_info=$(curl -s -X POST -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'api-key: f0ca152370904201a80de50ecae966fa' -d '{"kind": 0,"ipseg": "'${man_ipseg}'","ip_type": 2,"count":1,"apply_type": 0,"usage": "ExtendIP","bind_resource": "'${SN}'","remark": "apply_by_initos"}' 'http://api-gw.ucloudadmin.com/ipdb/intranet/ip')
    extend_ip=`echo $extend_ip_info | jq -r '.data[0].address'`
    if [[ -z $extend_ip || $extend_ip == 'null' ]];then
        PRINT_ERR "[ERROR] can not get extend_ip for '${man_ipseg}/${UCLOUD_BOND_RANGE}'"
        return 1
    else
        # check extend ip alive
        ping -c1 -w5 $extend_ip &>/dev/null
        if [[ $? -eq 0 ]];then
            PRINT_ERR "[ERROR] ExtendIP $extend_ip ping alive, please check ipdb."
            return 1
        fi

        sed -i "/UCLOUD_EXTEND_IP/d" /ucloud/exports.ini
        UCLOUD_EXTEND_IP=$extend_ip
        echo "UCLOUD_EXTEND_IP=$extend_ip" >> /ucloud/exports.ini
        # save to cmdb
        #PRINT_ERR "[ERROR] extend_ip $extend_ip save to cmdb failed"
        #return 1
    fi
    eval "$(ipcalc -m $man_ipseg)"
    cat > /etc/sysconfig/network-scripts/ifcfg-$extend_ifname << EOF
DEVICE=$extend_ifname
NM_CONTROLLED=no
ONBOOT=yes
BOOTPROTO=static
IPADDR=$UCLOUD_EXTEND_IP
NETMASK=$NETMASK
TYPE=Ethernet
EOF

#     # Policy Route
#     sed -i "/t_${extend_ifname}/d" /etc/iproute2/rt_tables
#     echo "251     t_${extend_ifname}" >> /etc/iproute2/rt_tables
#     cat > /etc/sysconfig/network-scripts/rule-$extend_ifname << EOF
# iif $extend_ifname table t_${extend_ifname}
# oif $extend_ifname table t_${extend_ifname}
# from $UCLOUD_EXTEND_IP table t_${extend_ifname}
# EOF
#     cat > /etc/sysconfig/network-scripts/route-$extend_ifname << EOF
# default via $UCLOUD_BOND_GATEWAY dev ${extend_ifname} table t_${extend_ifname}
# ${bond_ipseg}/${UCLOUD_BOND_RANGE} dev ${extend_ifname} table t_${extend_ifname}
# EOF
## 持久化抑制直连路由,BF卡有冲突，不修改


}

_check() {
    return 0
}

_check_bf(){
    _check="PASS"

    check_net_type || return 0
    # extend_ifname=p0m0
    # source /etc/sysconfig/network-scripts/ifcfg-$extend_ifname

    local ip_by_sn ipdb_ip_all
    ip_by_sn=$(curl -s -X GET -H 'Accept: application/json' -H 'api-key: f0ca152370904201a80de50ecae966fa' "http://api-gw.ucloudadmin.com/ipdb/intranet/ip?bind_resource=${SN}")
    ipdb_ip_all=$(echo "$ip_by_sn" | jq -r '.data[]|.address')
    # check ipdb bind SN
    PRINT_INFO ipdb_ip_all $ipdb_ip_all
    PRINT_INFO UCLOUD_IPMI $UCLOUD_IPMI
    PRINT_INFO UCLOUD_IPADDR $UCLOUD_IPADDR
    PRINT_INFO UCLOUD_EXTEND_IP $UCLOUD_EXTEND_IP
    for i in $UCLOUD_IPMI $UCLOUD_IPADDR $UCLOUD_EXTEND_IP
    do
        if ! echo "$ipdb_ip_all" | grep -qw "$i" ;then
            _check="FAIL"
            PRINT_ERR "[ERROR] SN $SN 未绑定 $i 请检查IPDB"
        fi
    done
    # check extend ip
    if [[ -n $extend_ifname ]] && [[ `echo "$ipdb_ip_all"| wc -w` -ne 3 ]];then
        _check="FAIL"
        PRINT_ERR "[ERROR] SN 绑定的IP数量不为3,请检查IPDB"
    fi

}


