#!/bin/bash
set +x
G_INSPECT_MMLPATH="/opt/product/snas/script/inspect_mml"
source "${G_INSPECT_MMLPATH}/CheckItems"

function GetDaemonPid()
{
    local RepeatTimes=(1 2 3)
    local daemonPid=$(pidof /opt/huawei/deploy/bin/daemon)
    local daemonPidCnt=$(echo ${daemonPid} | awk '{print NF}')
    for time in ${RepeatTimes[*]}; do
        if [ "${daemonPidCnt}" == "1" ]; then
            break
        fi
        sleep 2
        daemonPid=$( pidof /opt/huawei/deploy/bin/daemon )
        daemonPidCnt=$(echo ${daemonPid} | awk '{print NF}')
    done

    if [ "${daemonPidCnt}" != "1" ];then
        daemonPid="-1"
    fi
    echo ${daemonPid}
}

function EnvironVarPathRepair
{
    local curInspectNum="505"
    local curInspectFun="$(GetInspectType $curInspectNum)"
    local resultFile="/tmp/tmpResult${curInspectFun}"
    >"${resultFile}"
    local isPass=0
    local check_path="/usr/local/bin"

    #检查crontab中是否正常
    local cronRet=$(cat /etc/crontab | grep PATH= | grep -w "${check_path}")
    if [ "X$cronRet" == "X" ];then
        sed -i 's/PATH\=/PATH\=\/usr\/local\/bin\:/' /etc/crontab
        #（7.X之前版本）
        service cron restart
        if [ $? -ne 0 ];then
            isPass=1
            echo "[ERR]INFO:Failed to restart the cron service." >>${resultFile} 2>&1
        fi
    fi
    local cronPath=$(cat /etc/crontab | grep -Poa '(?<=^PATH=).*')
    cronRet=$(echo "$cronPath" |grep -w "${check_path}")
    if [ "X$cronRet" == "X" ];then
        isPass=1
        echo "[ERR]INFO:Failed to restore the crontab environment variable." >>${resultFile} 2>&1
    fi

    #daemon
    local daemonPid=$(GetDaemonPid)
    if [ "${daemonPid}" != "-1" ];then
        local daemonRet=$(cat -v /proc/${daemonPid}/environ 2>&1 | sed 's/\^@/\n/g' | grep -Poa '(?<=^PATH=).*' | grep -w "${check_path}")
        if [ "X$daemonRet" == "X" ];then
            #如果只是cron没有,则不需要重新启动daemon
            kill -9 $daemonPid
            #等待cron或snas_daemon服务的timer会自动拉起daemon,间隔最长1分钟时间
            for i in $(seq 1 20)
            do
                sleep 3
                daemonPid=$(GetDaemonPid)
                if [ "${daemonPid}" != "-1" ];then
                    break
                fi
            done
        fi
    fi

    local daemonPath=""
    if [ "${daemonPid}" != "-1" ];then
        daemonPath=$(cat -v /proc/${daemonPid}/environ 2>&1 | sed 's/\^@/\n/g' | grep -Poa '(?<=^PATH=).*' )
        dameRet=$(echo "$daemonPath" |grep -w "${check_path}")
        if [ "X$dameRet" == "X" ];then
            isPass=1
            echo "[ERR]INFO:Failed to restore the daemon environment variable." >>${resultFile} 2>&1
        fi
    else
        isPass=1
        echo "[ERR]INFO:No daemon process is found." >>${resultFile} 2>&1
    fi

    echo "daemon:${daemonPath}||crontab:${cronPath}" >>${resultFile} 2>&1
    echo "${curInspectFun}_Pass ${isPass}" >>${resultFile} 2>&1
}

EnvironVarPathRepair
exit 0