#!/bin/bash

# source env
SOURCE_LIB_CHECK=0

# Colorful Output
BOOTUP=color
RES_COL=60
MOVE_TO_COL="echo -en \\033[${RES_COL}G"
SETCOLOR_SUCCESS="echo -en \\033[1;32m"
SETCOLOR_FAILURE="echo -en \\033[1;31m"
SETCOLOR_WARNING="echo -en \\033[1;33m"
SETCOLOR_NORMAL="echo -en \\033[0;39m"

[[ ! $NR_FAIL ]] && NR_FAIL=0
[[ ! $NR_PASS ]] && NR_PASS=0

PRINT_PASS() {
    [ "$BOOTUP" = "color" ] && $MOVE_TO_COL
    echo -n "["
    [ "$BOOTUP" = "color" ] && $SETCOLOR_SUCCESS
    echo -n "  PASS  "
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo -n "]"
    echo -ne "\r"
    echo "$*"

    PRINT "<font color='green'>[PASS]</font>$*"
    (( NR_PASS += 1 ))
}

PRINT_FAIL() {
    [ "$BOOTUP" = "color" ] && $MOVE_TO_COL
    echo -n "["
    [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
    echo -n $"  FAIL  "
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo -n "]"
    echo -ne "\r"
    echo "$*"

    PRINT "<font color='red'>[FAIL]</font>$*"
    (( NR_FAIL += 1))
}

# Print All To LogFile
PRINT(){
    echo -n  "$*"'<br />' >> $INIT_LOG
}

# Print Error To LogFile
PRINT_ERR(){
    echo -n "<font color='red'>$*</font><br />" >> $INIT_LOG
    echo -e "\033[31m$*\033[0m"
}

# Print Info To LogFile
PRINT_INFO(){
    echo -n "<font color='green'>$*</font><br />" >> $INIT_LOG
    echo -e "\033[32m$*\033[0m"
}

# Get TID, UCLOUD_OSINIT_SERVICE
Get_IMAGE_PATH () {
    sed -i "/UCLOUD_OSINIT_SERVICE/d" /ucloud/exports.ini
    sed -i "/UCLOUD_TID/d" /ucloud/exports.ini
    if [[ -z $UCLOUD_TID ]];then
        # 增加接口查询tid 测试环境已不存在
        UCLOUD_TID=`curl -s http://${UCLOUD_OSINIT_SERVICE}/IdcDeploy/getTid/${SN}`
        echo -e >> /tmp/log-debug-upload.log '\n'`date +%F_%T` post $UCLOUD_OSINIT_SERVICE getTid: $UCLOUD_TID '\n'
    fi
    if [[ -n $UCLOUD_TID && -n $UCLOUD_OSINIT_SERVICE ]];then
        echo UCLOUD_OSINIT_SERVICE=$UCLOUD_OSINIT_SERVICE >> /ucloud/exports.ini
        echo UCLOUD_TID=$UCLOUD_TID >> /ucloud/exports.ini
    elif [[ $PANGU && -z $UCLOUD_TID ]];then
        PRINT_ERR "[ERROR] UCLOUD_TID Is NULL.请先检查机器SN,数据库,接口"
        return 1
    elif [[ $PANGU && -z $UCLOUD_OSINIT_SERVICE ]];then
        PRINT_ERR "[ERROR] UCLOUD_OSINIT_SERVICE Is NULL."
        return 1
    fi
    for lines in `cat /ucloud/exports.ini`
    do
        export $lines
    done
}

mask_handle() {
    total=0
    i=0
    while [ $i -lt $1 ]
    do
        let total+=$((2**$i))
        let i+=1
    done
    echo $((255-total))
}

get_gateway_and_mask() {
    local ipaddr=$1
    local subnet=$2
    ip1=`echo $ipaddr | cut -d '.' -f 1`
    ip2=`echo $ipaddr | cut -d '.' -f 2`
    ip3=`echo $ipaddr | cut -d '.' -f 3`
    ip4=`echo $ipaddr | cut -d '.' -f 4`

    if [ $subnet -gt 0 -a $subnet -le 8 ];then
        length=$((32-24-subnet))
        mask=`mask_handle $length`
        cs=$((2**length))
        gateip=$((ip1/cs*cs))
        gw_ip="$gateip.0.0.1"
        subnet_mask="$mask.0.0.0"
    elif [ $subnet -gt 8 -a $subnet -le 16 ];then
        length=$((32-16-subnet))
        mask=`mask_handle $length`
        cs=$((2**length))
        gateip=$((ip2/cs*cs))
        gw_ip="$ip1.$gateip.0.1"
        subnet_mask="255.$mask.0.0"
    elif [ $subnet -gt 16 -a $subnet -le 24 ];then
        length=$((32-8-subnet))
        mask=`mask_handle $length`
        cs=$((2**length))
        gateip=$((ip3/cs*cs))
        gw_ip="$ip1.$ip2.$gateip.1"
        subnet_mask="255.255.$mask.0"
    elif [ $subnet -gt 24 -a $subnet -le 32 ];then
        length=$((32-subnet))
        mask=`mask_handle $length`
        cs=$((2**length))
        gateip=$((ip4/cs*cs+1))
        gw_ip="$ip1.$ip2.$ip3.$gateip"
        subnet_mask="255.255.255.$mask"
    else
        echo "[ERROR] subnet not supported"
        exit 1
    fi

    echo $gw_ip,$subnet_mask
    return 0
}

# Get Environment Info
Get_Env_Info() {
    # Run Only As root
    if [[ $(id -u) != 0 ]];then
        PRINT_ERR "[ERROR] Excute User Not root."
        return 1
    fi

    # Virtual Machine=1,Physical Machine=0
    if dmidecode -t1 | grep -iEq "Red Hat|KVM|vmware"
    then
        VMFLAG=1
    else
        VMFLAG=0
    fi

    # get ARCH , x86_64 or aarch64
    ARCH=`lscpu|grep 'Architecture:'|awk '{print $2}'`
    if [[ -z $ARCH ]];then
        PRINT_ERR "[ERROR] get Arch failed"
        return 1
    fi

    # lspci 命令输出 BlueField 字符即是BF卡的机器，则 BFFLAG 设置为 1
    if lspci -nn -d 15b3::0604 |grep -oPq 'BlueField(?:-(\d+))?'
    then
        BFFLAG=1
    else
        BFFLAG=0
    fi

    # BOOTMODE: Legacy or UEFI
    BOOTMODE="Legacy"
    [[ -d "/sys/firmware/efi" ]] && BOOTMODE="UEFI"

    # OS Version
    local
    os_release=$(cat /etc/redhat-release|head -n 1)
    if [[ $os_release =~ "CentOS release 6" ]];then
        OS=CentOS6
    elif [[ $os_release =~ "CentOS Linux release 7" ]];then
        OS=CentOS7
    else
        PRINT_ERR "[ERROR] OS Not Match, Only Support For CentOS6.x OR CentOS7.x"
        return 1
    fi

    # init yum
    source $BASEDIR/modules/base/004-yum-config.sh
    _install
    yum install -y python-requests 1>/dev/null

    # Get IP Address
    HOSTIP=`ip -o r get 192.168.168.106|sed -n 's/.*src \([0-9.]*\) .*/\1/p'`
    HOSTIP_RANGE=`ip addr |grep $HOSTIP|awk '{print $2}'|awk -F '/' '{print $NF}'`

    # 云主机跳过获取cmdb
    echo $HOSTIP |grep -q '^100\.'
    [[ $? -eq 0 ]] && return 0

    # VM No Need Get Below Info
    if [[ $VMFLAG = 1 ]];then
        python $BASEDIR/utils/cmdb_api.py "VMServer" $ENVFLAG
        [ $? -ne 0 ] && PRINT_ERR "[ERROR] CMDB API Error, Check API Response."

        OperationalStatus=$(cat $INIT_TMP_DIR/cmdb.info|egrep ^OperationalStatus|awk -F ":" '{print $2}')
        if [[ $OperationalStatus = '上线' || $OperationalStatus = '交付' ]];then
            PRINT_ERR "[ERROR] 交付和上线状态不允许执行"
            echo -e "\033[31m [ERROR] 交付和上线状态不允许执行 \033[0m"
            exit 1
        fi

        if [ -s $INIT_TMP_DIR/cmdb.info ];then
            Usage=$(cat $INIT_TMP_DIR/cmdb.info|egrep ^Usage|awk -F ":" '{print $2}')
            SecUsage=$(cat $INIT_TMP_DIR/cmdb.info|egrep ^SecUsage|awk -F ":" '{print $2}')
            REGION=$(cat $INIT_TMP_DIR/cmdb.info|egrep ^IDC|awk -F ":" '{print $2}')
            OWNER=$(cat $INIT_TMP_DIR/cmdb.info|egrep ^Owner|awk -F ":" '{print $2}')
        else
            source /ucloud/init_info
        fi

        # CMDB Value Not NULL
        local check_arr=(Usage SecUsage REGION)
        for info in ${check_arr[@]};
        do
            eval local value=\$$info
            if [[ -z $value ]];then
                PRINT_ERR "$info Has No Value."
                return 1
            fi
        done
    else
        # Get CMDB Info
        python $BASEDIR/utils/cmdb_api.py "Server" $ENVFLAG
        [ $? -ne 0 ] && PRINT_ERR "[ERROR] CMDB API Error, Check API Response."

        OperationalStatus=$(cat $INIT_TMP_DIR/cmdb.info|egrep ^OperationalStatus|awk -F ":" '{print $2}')
        if [[ $OperationalStatus = '上线' || $OperationalStatus = '交付' ]];then
            PRINT_ERR "[ERROR] 交付和上线状态不允许执行"
            echo "\033[31m [ERROR] 交付和上线状态不允许执行 \033[0m"
            exit 1
        fi

        if [ -s $INIT_TMP_DIR/cmdb.info ];then
            Usage=$(cat $INIT_TMP_DIR/cmdb.info|egrep ^Usage|awk -F ":" '{print $2}')
            SecUsage=$(cat $INIT_TMP_DIR/cmdb.info|egrep ^SecUsage|awk -F ":" '{print $2}')
            REGION=$(cat $INIT_TMP_DIR/cmdb.info|egrep ^IDC|awk -F ":" '{print $2}')
            BondIP=$(cat $INIT_TMP_DIR/cmdb.info|egrep ^BondIP|awk -F ":" '{print $2}')
            IPMI=$(cat $INIT_TMP_DIR/cmdb.info|egrep ^IPMI|awk -F ":" '{print $2}')
            AN=$(cat $INIT_TMP_DIR/cmdb.info|egrep ^AN|awk -F ":" '{print $2}')
            SN=$(cat $INIT_TMP_DIR/cmdb.info|egrep ^SN|awk -F ":" '{print $2}')
            Manufacture=$(cat $INIT_TMP_DIR/cmdb.info|egrep ^Manufacture:|awk -F ":" '{print $2}')
            ManufactureType=$(cat $INIT_TMP_DIR/cmdb.info|egrep ^ManufactureType|awk -F ":" '{print $2}')
            MachineType=$(cat $INIT_TMP_DIR/cmdb.info|egrep ^MachineType|awk -F ":" '{print $2}')
            OWNER=$(cat $INIT_TMP_DIR/cmdb.info|egrep ^Owner|awk -F ":" '{print $2}')
            RaidInfo=$(cat $INIT_TMP_DIR/cmdb.info|egrep ^RaidInfo|awk -F ":" '{print $2}')
            Memory=$(cat $INIT_TMP_DIR/cmdb.info|egrep ^Memory|awk -F ":" '{print $2}')

            [[ -n $PANGU ]] && Get_IMAGE_PATH
            local check_arr=(Usage SecUsage IDC HOSTIP AN SN Manufacture: ManufactureType RaidInfo Memory)
            for info in ${check_arr[@]};
            do
                if [[ -z $(cat $INIT_TMP_DIR/cmdb.info|egrep ^$info|awk -F ":" '{print $2}') ]];then
                    PRINT_ERR "$info Has No Value."
                    return 1
                fi
            done
        else
            if [[ -f /ucloud/init_info ]];then
                source /ucloud/init_info
            else
                PRINT_ERR "[ERROR] CMDB API Error, File /tmp/os_init/cmdb.info Not Found, Maybe dmidecode SN Not exist!!!"
                return 1
            fi
        fi
        
        if [[ $BFFLAG = 0 ]];then        
            # CPU Model
            if [[ $(cat /proc/cpuinfo | grep 'model name' | uniq | grep -c v2) -ne 0 ]];then
                CpuModel="CpuV2"
            elif [[ $(cat /proc/cpuinfo | grep 'model name' | uniq | grep -c v3) -ne 0 ]];then
                CpuModel="CpuV3"
            elif [[ $(cat /proc/cpuinfo | grep 'model name' | uniq | grep -c v4) -ne 0 ]];then
                CpuModel="CpuV4"
            elif [[ $(cat /proc/cpuinfo |grep 'model name' | uniq| grep -iEc "platinum|gold|silver|bronze") -ne 0 ]];then
                CpuModel="CpuV5"
            fi


        fi
    fi
    
    # OVS Support
    local ovsconfig=`/usr/bin/python $BASEDIR/utils/GetApolloConf.py "ovsconfig" "ovs"`
    if [[ $ovsconfig =~ "$Usage-$SecUsage" || $ovsconfig =~ "$Usage"-all ]] \
        || [[ $Usage = unet && $OS = CentOS6 && $VMFLAG = 0  ]];then
        OVS="ovs"
    else
        OVS="no_ovs"
    fi

    # Off-Standard Region, Such As POP Point, Access To Standard Region
    local initregion=`/usr/bin/python $BASEDIR/utils/GetApolloConf.py "initregion" "$REGION" 2>/dev/null`
    [[ -n $initregion ]] && REGION=$initregion

    return 0
}

# Upload Info To Frontend
UPLOAD_LOG () {
    local req content tid init_stat
    init_stat=$1
    # local action=$2
    info=""
    echo -e >> /tmp/log-debug-upload.log '\n'`date +%F_%T` lib.sh upload log start stat: $1 ACTION: $ACTION .
    if [[ $init_stat == "FAIL" && $ACTION == "install" ]];then
        SubStatus='init_fail' #初始化失败
        info="初始化失败,请查看错误日志,一般重试可解"
    elif [[ $init_stat == "PASS" && $ACTION == "install" ]];then
        SubStatus='init_success' #初始化成功
    elif [[ $init_stat == "FAIL" && $ACTION == "check" ]];then
        SubStatus='away_check_fail' #交付检测失败
        info="交付检测失败,请查看错误日志"
    elif [[ $init_stat == "PASS" && $ACTION == "check" ]];then
        SubStatus='away_check_success' #交付检测成功
    elif [[ $init_stat == "GPU" && $ACTION == "check" ]];then
        SubStatus='away_gpu_loading' # 加载压测环境
        info="GPU压测中耐心等待$(date +%F_%T_%Z)"
    elif [[ $init_stat == "BIOS" && $ACTION == "install" ]];then
        SubStatus='wait_init_start_timing' # BIOS升级成功等待重启后重试
        info="固件升级成功等待重启后重新初始化$(date +%F_%T_%Z)"
    fi

    # Upload SubStatus To Frontend
#    echo -e >> /tmp/log-debug-upload.log '\n'`date +%F_%T` lib.sh post updateDeployServer_init url: $UCLOUD_OSINIT_SERVICE SN: $SN SubStatus: $SubStatus $PANGU _start '\n'
    if [[ $PANGU = "sodpangu" ]];then
        req=$(cat <<EOF
{
    "Action": "updateDeployServer",
    "DataSet": [
        {
            "Action": "init",
            "SubStatus": "${SubStatus}",
            "SN": "${SN}",
            "Code": 0,
            "Info": "${info}"
        }
    ],
    "Token": "02135cd55baa4d91987aac0b93af7d14"
}
EOF
)
    else
        req=$(cat <<EOF
{
    "Action": "updateDeployServer",
    "DataSet": [
        {
            "Action": "init",
            "SubStatus": "${SubStatus}",
            "SN": "'${SN}'",
            "Info": "${info}"
        }
    ]
}
EOF
)
    fi
    curl http://${UCLOUD_OSINIT_SERVICE}/IdcDeploy/execTask/ -d "$req" &>> /tmp/log-debug-upload.log
    echo -e >> /tmp/log-debug-upload.log '\n'`date +%F_%T` lib.sh post updateDeployServer_init url: $UCLOUD_OSINIT_SERVICE SN: $SN SubStatus: $SubStatus $PANGU _end '\n'

    content=$(cat /tmp/os_init/init.log|tr '\n' ' ')
    tid=$(cat /ucloud/exports.ini | grep UCLOUD_TID= | uniq |awk -F "=" '{print $2}'|tail -n 1)
    echo -e >> /tmp/log-debug-upload.log '\n' `date +%F_%T` content: "$content" `sed 's#<br />#\n#g' /tmp/os_init/init.log`
    echo -e >> /tmp/log-debug-upload.log '\n' `date +%F_%T` lib.sh post receiveLog_init url: $UCLOUD_OSINIT_SERVICE tid: $tid _start '\n'
    if [[ $PANGU = "sodpangu" ]];then
        req=$(cat <<EOF
{
    "Token": "02135cd55baa4d91987aac0b93af7d14",
    "Action": "receiveLog",
    "DataSet": {
        "Ret": "${content}",
        "DeployStatus": "init",
        "SubStatus": "",
        "Code": 0,
        "TaskId": ${tid},
        "sn": "${SN}"
    }
}
EOF
)
    else
        req=$(cat <<EOF
{
    "Action": "receiveLog",
    "DataSet": {
        "Ret": "${content}",
        "DeployStatus": "init",
        "SubStatus": "",
        "TaskId": ${tid},
        "sn": "${SN}"
    }
}
EOF
)
    fi
    ret=$(curl http://${UCLOUD_OSINIT_SERVICE}/IdcDeploy/execTask/ -d "$req" 2>> /tmp/log-debug-upload.log)
    osinit_pid_delete
    if [[ $ret != '"true"' ]]; then
        PRINT_ERR "[ERROR] Upload Init Log Failed."
        echo -e >> /tmp/log-debug-upload.log "\n`date +%F_%T` post not_true ret: $ret url: $UCLOUD_OSINIT_SERVICE req: $req \n"
        exit 1
    fi
}

UPLOAD_PROCESSING () {
    local stat=$1
    local module=$2
    local successed_total=$3
    local failed_total=$4
    local total=$5
    local req
    req=$(cat <<EOF
{
    "Action": "updateDeployServer",
    "DataSet": [
        {
            "Info": "$module",
            "SN": "${SN}",
            "SubStatus": "${stat}",
            "Code": 0,
            "Progress": [$successed_total,$failed_total,$total]
        }
    ],
    "Token": "02135cd55baa4d91987aac0b93af7d14"
}
EOF
)
    curl http://${UCLOUD_OSINIT_SERVICE}/IdcDeploy/execTask/ -d "$req"  &>> /tmp/log-debug-upload.log
}

WALLE_LLDP_RUN() {
    if [[ $VMFLAG -eq 1 ]] ;then
        return 0
    fi
    # 通过 omega 下发命令，执行 collect_sys_lldpd.sh 获取交换机信息并更新到 CMDB
    ret=$(curl -s -X POST -H "cloudbase-auth: 0ee8b6ae-6429-4f03-a9b2-599a1f0d6092" -H 'Content-Type: application/json' "http://kong-gw.service.ucloud.cn/cloudbase/atomtasks/24538067" -d '{"IP": "'$HOSTIP'"}' )
    if [[ `echo "$ret" | jq .meta.code` -ne 0 ]];then
        PRINT_ERR "[ERROR] Walle lldp run Failed. $ret"
        return 1
    fi
    PRINT_INFO "[INFO] Walle lldp run Succeed."
}

Done_check() {
    find / -name ucloud-basic-init.sh -exec rm -f {} +
    rm -rf "$INIT_TMP_DIR" > /dev/null 2>&1
    rm -rf /tmp/fw_update > /dev/null 2>&1
    \rm -f /tmp/*.log
    mkdir -p /ucloud
    echo "UCLOUD_INIT=1" >> /ucloud/exports.ini
    sed -i '/pangu-key-v3@2025-08-28/d' /root/.ssh/authorized_keys
    sed -i '/Uops_PanGu-v2_2022-10-17/d' /root/.ssh/authorized_keys
    shutdown -r 1 "PANGU init check successed. The system is about to reboot 盘古交付检测完成 系统即将重启"
    cat /dev/null > ~/.bash_history && history -c
}
