#!/usr/bin/env bash
pid_file=/var/run/ksvd/ksvd-get-disk_health.pid
disk_health=/var/lib/ksvd/disk_health
if [ -f ${pid_file} ];then
    pid=$(cat ${pid_file})
    if [[ ${pid} != "" ]];then
        kill -0 ${pid}
        if [ $? -eq 0 ];then
            exit 0
        else
            rm -rf ${pid_file} 
        fi
    fi 
fi

# 获取磁盘健康状况
function get_disk_health(){
    if [ -f ${disk_health} ];then
        rm -rf ${disk_health}
    fi
    cat >${disk_health} <<EOF
#name|status
EOF
    for disk in $(lsblk | grep disk | awk '{print $1}');do
        disk_path="/dev/"${disk}
        # first check has running smartctl
        ps -ef | grep -v grep | grep /usr/sbin/smartctl | grep -q $disk_path && echo 'Running' && exit 0
        
        # then check disk health
        stat=$(timeout -s SIGKILL 5 timeout -s SIGKILL 4 bash -c "/usr/sbin/smartctl -H ${disk_path}" |grep -E 'PASSED|OK'|awk -F ':' '{print $2}'|tr -d ' ')
        if [[ ${stat} = "" ]];then
            for N in 0 1 2 3 4 5 6 7 8 9 10;do 
                stat=$(timeout -s SIGKILL 5 timeout -s SIGKILL 4 bash -c "/usr/sbin/smartctl -H ${disk_path} -d  megaraid,${N}" |grep -E 'PASSED|OK'|awk -F ':' '{print $2}'|tr -d ' ')
                if [[ ${stat} = "" ]];then
                    continue
                else
                    echo ${disk}"|"${stat} >> ${disk_health}
                    break
                fi
            done
        else
            echo ${disk}"|"${stat} >> ${disk_health}
        fi
        if [[ ${stat} = "" ]];then
            sleep 1
            echo ${disk}"|FAIL" >> ${disk_health}
        fi
    done
}
function main(){
    while true;do
        get_disk_health
        sleep 10
    done
}
main
