#!/bin/bash

LOG_FILE="/var/log/inspect.log"

GetInspectType()
{
    case $1 in
    123)
        #检查 rmbg任务并发数
        echo "CheckSysDiskHealth"
        ;;
    139)
        #检查 rmbg任务并发数
        echo "checkRMGB"
        ;;
    148)
        #SMR磁盘运行状态检查
        echo "CheckSMRdiskinfo"
        ;;
    157)
        #节点电子标签检查
        echo "CheckElecLabel"
        ;;
    203)
        #4.Check Watchdog Status
        echo "checkWatchdogStatus_Async"
        ;;
    244)
        #检查删除任务
        echo "checkDelTask"
        ;;
    302)
        #操作系统环境变量检查
        echo "CheckEnvironVarPath"
        ;;
    270)
        echo "CheckNodeState"
        ;;
    274)
        echo "CheckCertificate"
        ;;
    294)
        echo "checkDiskNokickStatus"
        ;;
    311)
        echo "CheckBirthTime"
        ;;
    312)
        echo "checkKernelHotPatch"
        ;;
    313)
        echo "CheckDepXML"
        ;;
    315)
        echo "nas_check_quota_scan"
        ;;
    316)
        echo "CheckMasterSpecialConfig"
        ;;
    317)
        echo "CheckALLNodeSpecialConf"
        ;;
    318)
        echo "nasCheckPage"
        ;;
    319)
        echo "CheckValueaddedfeatures"
        ;;
    320)
        echo "CheckMdsSoftReset"
        ;;
    321)
        echo "DeepCheckHardDriveFirmware"
        ;;
    322)
        echo "CheckZoneMount"
        ;;
    323)
        echo "CheckBMCDataAcquisitionSwitch"   
        ;;
    326)
        echo "CheckRouteConfigured"
        ;;
    327)
        echo "CheckCCDBDBConsistency"
        ;;
    328)
        echo "checkDiskModePage"
        ;;
    334)
        echo "CheckStaticCfg"
        ;;
    335)
        echo "CheckUpdFile"
        ;;
    339)
        echo "CheckConcomitantLogs"
        ;;
    340)
        echo "CheckV5NvdimmFirmware"
        ;;
    341)
        echo "CheckIfUpgradeInterfaceCardAndChipCard"
        ;;
    350)
        echo "CheckStorageVersion"
        ;;
    351)
        echo "CheckHardWareVersion"
        ;;
    352)
        echo "CheckFrontAndBackPort"
        ;;
    353)
        echo "CheckFrontIPNumber"
        ;;
    354)
        echo "CheckBackNetworkIPaddr"
        ;;
    355)
        echo "CheckClusterRedundancyRatio"
        ;;
    356)
        echo "CheckClusterNodeNumber"
        ;;
    357)
        echo "CheckNodePoolDiskConsistency"
        ;;
    358)
        echo "CheckManagerNet"
        ;;
    359)
        echo "CheckCMiniFile"
        ;;
    407)
        echo "CheckConfigurationCompatibility"
        ;;
    501)
        echo "certUpdate"
        ;;
    502)
        echo "ConfigurationCompatibilityRepair"
        ;;
    504)
        echo "HPatchStatusRepair"
        ;;
    505)
        echo "EnvironVarPathRepair"
        ;;
    *)
        echo ""
        ;;
    esac
}

function set_ifs
{
    IFS_OLD=$IFS
    IFS=$'\n'
}

function restore_ifs
{
    IFS=$IFS_OLD
}

function LOG
{
    echo [`date`][$0]$@ >> $LOG_FILE
}
#判断CM主返回1：CM主  0：非主
function isMaster()
{
    local tmpInfo=""
    local masterNodeName=""
    local localnodeName=$(hostname)
    tmpInfo=$(/usr/local/bin/MmlBatch 4016 "cm master" | grep "Node Name" | sed -e 's/\x1B\[0;[3-4][0-9]m//g' -e 's/\x0D//g' -e 's/\x00//g')
    masterNodeName=$(echo "${tmpInfo}" | sed 's/Node Name: //')
    if [ "${masterNodeName}" = "${localnodeName}" ];then
        return  0
    else
        return  1
    fi
}
function check_pass()
{
    local list=(["2"]=0 ["1"]=1 ["4"]=2 ["0"]=3 ["3"]=4) #未检查(2)>不通过(1)>建议优化(4)>通过(0)>不涉及(3)
    local isPass=$1   #集群结果
    local tmpIsPass=$2 #当前检查结果

    if [ ${list[$tmpIsPass]} -lt ${list[$isPass]} ];then
        isPass=$tmpIsPass
    fi
    echo $isPass
}
#获取后端可以ping通的后端ip
function GetLocalIp()
{
    local snas_ini_file="/opt/huawei/snas/etc/snas.ini"
    local IpIndex=1
    local subnetwork_id
    local BackendIp
    local IpNum
    IpNum=`cat ${snas_ini_file} | grep "ipaddr_" | wc -l`

    while [ "$IpIndex" -le "$IpNum" ]; do
        subnetwork_id=`grep "subnetwork_id_${IpIndex}" ${snas_ini_file} 2>/dev/null | awk -F "=" '{print $2}'`
        if [ -z "${subnetwork_id}" ]; then
            continue
        fi

        if [ ${subnetwork_id} -eq 1 ]; then
            BackendIp=`grep "ipaddr_${IpIndex}" ${snas_ini_file} 2>/dev/null | awk -F "=" '{print $2}'`
            ping "${BackendIp}" -f -c 2 -w 2 >/dev/null 2>&1
            if [ $? -ne 0 ]; then
                IpIndex=$((IpIndex + 1))
                continue
            else
                echo ${BackendIp}
                break
            fi
        fi

        IpIndex=$((IpIndex + 1))
    done
}
function get_node_backnet_ip
{
    local nid=$1
    local temp=1
    local iRet=0
    sqlite3 /opt/huawei/snas/etc/cm_conf.db "select IP_ADDR from CM_NODE_IP_T where NID=$nid and SUBNET_ID=1 order by NID limit 1"
    iRet=$?
    while [[ ${iRet} -ne 0 ]]
    do
        sleep 2
        LOG "[$FUNCNAME]Failed to get back subnet IP of $nid from db"
        temp=$((temp + 1))
        if [ $temp -gt 5 ];then
            break
        fi
        sqlite3 /opt/huawei/snas/etc/cm_conf.db "select IP_ADDR from CM_NODE_IP_T where NID=$nid and SUBNET_ID=1 order by NID limit 1"
        iRet=$?
    done
    return $iRet
}

function ChangeProperty()
{
    local change_type=$1
    local property=""
    LOG "TYPE:${change_type},FILE:${Paras}"


    for changepath in ${Paras}
    do
        if [ -d ${changepath} ];then
            path_type=0
            property=$( lsattr -a ${changepath} | grep "/.$" |awk '{print $1}' )
        else
            path_type=1
            property=$( lsattr -a ${changepath} | awk '{print $1}' )
        fi
        if [ "X${property}" == "X" ];then
            continue
        fi
        if [ "${change_type}" == "add" ];then
            if [[ ${property} =~ "i" ]];then
                continue
            fi
            if [ "${path_type}" == "0" ];then
                chattr +i ${changepath} >/dev/null 2>&1
            else
                chattr -f +i ${changepath} >/dev/null 2>&1
            fi
        elif [ "${change_type}" == "del" ];then
            if [[ ${property} =~ "i" ]];then
                if [ "${path_type}" == "0" ];then
                    chattr -i ${changepath} >/dev/null 2>&1
                else
                    chattr -f -i ${changepath} >/dev/null 2>&1
                fi
            fi
        else
            continue
        fi
    done
    return
}



Add_i_attr="add"
Del_i_attr="del"
G_MML_PATH="/opt/huawei/snas/script/inspect_mml"
Paras=${@:2}
taskids=$1

#更改入口脚本的i属性
if [ "${taskids}" == "${Add_i_attr}" -o "${taskids}" == "${Del_i_attr}" ];then
    ChangeProperty "${taskids}"
    exit 0
fi
if [ "${taskids}" == "CheckStripeCfg" ]; then
    /opt/huawei/snas/script/inspect_mml/CheckStripeCfg
    exit $?
fi
if [ "${taskids}" == "CheckXinfoXattr" ]; then
    /opt/huawei/snas/script/inspect_mml/CheckXinfoXattr
    exit $?
fi
if [ "$taskids" = "checkCoreFile" ] && [ "X$2" != "X" ]; then
    # 233 检查是否有CORE文件   分别在/corefile/crash和/corefile目录中查找是否有近30天的文件产生
    find /corefile/crash -mtime -30 -type f -print | grep -w "vmcore" | grep .e$ > $2 2>&1
    find /corefile -maxdepth 1 -mtime +-1 -mtime -30 ! -type d -print| grep -v "ipmitool" >> $2 2>&1
    df -m /corefile | grep "/corefile" | awk '{print "AvailableSpace="$4}' >> $2 2>&1
    exit 0
fi
if [ "${taskids}" == "updateCert" -o  "${taskids}" == "restoreCert" ]; then
    /opt/huawei/snas/script/inspect_mml/certRmtUpdate.sh $@
    exit $?
fi
# checkSoftwareStatusEx接口管理节点一次性发来的taskids数量最多达到36个，非CM主节点一次性发来的taskids数量最多达到33个，这一波
# 巡检项执行时间都不算长（大部分1s内），加上整体单项巡检超时时长为1500s，所以不能全部并行，隔一秒开一个并行，整体并发度就会降下来
for taskid in $taskids
do
{
    {
        InspectFun=`GetInspectType $taskid`

        if [ "${InspectFun}" != "" ]; then
            #获取此脚本的运行参数
            CurParam=""
            ss=${InspectFun}-
            for Param in $Params
            do
            {
                tmpStr=$(echo $Param |grep $InspectFun)
                if [ "$tmpStr" != "" ];then
                    CurParam=$(echo $Param |awk -F "$ss" '{printf $2}'|sed 's/-/ /g')
                    break;
                fi
            }
            done

            InspectBeginTime=$(date +%s)
            $G_MML_PATH/$InspectFun "$CurParam"
            InspectEndTime=$(date +%s)
            difftime=$(($InspectEndTime - $InspectBeginTime))
            LOG "CheckItems ${taskid},InspectBeginTime:${InspectBeginTime},InspectEndTime:${InspectEndTime},difftime:${difftime}"
            #判断巡检项是否通过，若不通过，并且前一次巡检时间小于250秒，那么重新再巡检一次
            PassCode=$(cat /tmp/tmpResult${InspectFun} |grep ${InspectFun}_Pass |awk '{printf $2}')
            if [ "$PassCode" = "1" ] && [ $difftime -lt 250 ];then
                $G_MML_PATH/$InspectFun "$CurParam"
            fi
        fi
    }&

    sleep 1
}
done
wait

for taskid in $1
do
{
    InspectFun=`GetInspectType $taskid`

    if [ "${InspectFun}" != "" ]; then
        echo  ${InspectFun}
        cat "/tmp/tmpResult${InspectFun}"
        echo  ${InspectFun}_End
    fi

}
done
