#!/bin/bash
set +x

G_INSPECT_MMLPATH="/opt/huawei/snas/script/inspect_mml"
source $G_INSPECT_MMLPATH/CheckItems
CurInspectNum="302"
CurInspectFun="$(GetInspectType $CurInspectNum)"
RESULTFILE="/tmp/tmpResult${CurInspectFun}"
>${RESULTFILE}

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

function LOG
{
   time=$(date)
   echo [${time}][$$]$@ >> ${LOG_FILE}
}


function main
{
    local RepeatTimes=(1 2 3)
    local daemonNumCnt=0
    local daemonNum=""
    local checkInfo1=""
    local checkInfo2=""
    local isPass=0
    local result1="YES"
    local result2="YES"

    daemonNum=$( pidof /opt/huawei/deploy/bin/daemon )
    if [ X"${daemonNum}" = "X" ];then
        result1="pidof /opt/huawei/deploy/bin/daemon failed."
        isPass=1
        LOG "[$FUNCNAME] pidof /opt/huawei/deploy/bin/daemon failed."
    else
        daemonNumCnt=$(echo ${daemonNum} | awk '{print NF}')
        # 如果daemon PID不唯一，属于异常，允许重试3次
        for time in ${RepeatTimes[*]}; do
            if [ "${daemonNumCnt}" != "1" ]; then
                sleep 2
                daemonNum=$( pidof /opt/huawei/deploy/bin/daemon )
                daemonNumCnt=$(echo ${daemonNum} | awk '{print NF}')
                continue
            fi
            break
        done
        if [ "${daemonNumCnt}" = "1" ]; then  #正常了才检查，仍然不正常则结果显示获取的异常PID
            checkInfo1=$(cat -v /proc/${daemonNum}/environ | sed 's/\^@/\n/g' |  grep -Poa '(?<=^PATH=).*' )
            if [[ ! "${checkInfo1}" =~ "/usr/local/bin" ]];then
                result1="${checkInfo1:---}"
                isPass=1
            fi
        else
            result1="pid(${daemonNum})"
            isPass=1
        fi

    fi

    checkInfo2=$( cat /etc/crontab | grep PATH= )
    if [[ ! "${checkInfo2}" =~ "/usr/local/bin" ]];then
        result2="${checkInfo2:---}"
        isPass=1
    fi

    echo "daemon:${result1}||crontab:${result2}" >>${RESULTFILE}
    echo "${CurInspectFun}_Pass ${isPass}" >>${RESULTFILE} 2>&1
    LOG "[$FUNCNAME]${CurInspectFun}_Pass ${isPass}"
}

main
