#!/bin/sh

. /etc/PG.conf

RAMDISK="/usr/ramdisk"
TMPDIR="${RAMDISK}/tmp/sys_check/"
APIDIR="${TMPDIR}/api"
LOGDIR="${TMPDIR}/log"

FLOWEYE="${RAMDISK}/bin/floweye"


sys_base_check()
{
    api_file="${APIDIR}/base_${SYS_TIME}.ok"
    tmp_file="${api_file}.tmp"

    cur_time=`date +%s`
    cpu_rate=`${FLOWEYE} cpu stat | grep cpurate | cut -d"=" -f2`
    cpu_temp=`${FLOWEYE} cpu stat | grep temperature | cut -d"=" -f2`
    mem_rate=`${FLOWEYE} cpu stat | grep memrate | cut -d"=" -f2`
    mem_total=`${FLOWEYE} cpu stat | grep physmemM | cut -d"=" -f2`
    beep_stat=`${FLOWEYE} beep stat | grep stopped | cut -d"=" -f2`
	
    printf "{\"type\":\"base\",\"value\":{" > ${tmp_file}
    printf "\"sys_time\":${cur_time}" >> ${tmp_file}
    printf ",\"cpu_rate\":${cpu_rate}" >> ${tmp_file}
    printf ",\"cpu_temp\":${cpu_temp}" >> ${tmp_file}
    printf ",\"mem_rate\":${mem_rate}" >> ${tmp_file}
    printf ",\"mem_total\":${mem_total}" >> ${tmp_file}
    printf ",\"beep_stat\":${beep_stat}" >> ${tmp_file}
    printf "}}" >> ${tmp_file}

    mv ${tmp_file} ${api_file}
}


sys_process_check()
{
    api_file="${APIDIR}/eprocess_${SYS_TIME}".ok
    tmp_file="${api_file}.tmp"
    
    errfind=0
    pool="panaos ipe_monitor datamon ipe_xping ipe_mgd"

    printf "{\"type\":\"eprocess\",\"value\":{" > ${tmp_file}

    for p in ${pool}
    do
        stat=`ps -ax | grep ${p} | grep -v grep`

        printf "${dot}" >> ${tmp_file}

        if [ "${stat}" = "" ]; then
            printf "\"${p}\":0" >> ${tmp_file}
            errfind=$((${errfind} + 1))
        else
            printf "\"${p}\":1" >> ${tmp_file}
        fi

        [ "${dot}" = "" ] && dot=","
    done

    printf "},\"errfind\":${errfind}}" >> ${tmp_file}
    mv ${tmp_file} ${api_file}
}


disk_auto_clear()
{
    api_file="${APIDIR}/clear_${SYS_TIME}.ok"
    tmp_file="${api_file}.tmp"
    
    total_size=0

    printf "{\"type\":\"disk_clear\",\"value\":[" > ${tmp_file}
    printf "{\"name\":\"\",\"size\":0}" >> ${tmp_file}

    file_pool="/usr/ramdisk/bin/dpi.so.old"
    file_pool="${file_pool} /usr/ramdisk/bin/dpi.so.new"
    file_pool="${file_pool} ${PGPATH}/bin/dpi.so.old"
    file_pool="${file_pool} ${PGPATH}/bin/dpi.so.new"
    file_pool="${file_pool} `find /tmp -type f 2>/dev/null`"
    file_pool="${file_pool} `find / -name "*.core" 2>/dev/null`"
    file_pool="${file_pool} `find / -name "*.fetch*" 2>/dev/null`"
    file_pool="${file_pool} `find "${DATAPATH}" -name "*.log" -mtime +181 -type f -maxdepth 1 2>/dev/null`"

    if [ -d ${RAMDISK}/sysupgrade ]; then
        file_pool="${file_pool} `find ${RAMDISK}/sysupgrade -type f 2>/dev/null`"
    fi
    if [ -d ${RAMDISK}/appupgrade ]; then
        file_pool="${file_pool} `find ${RAMDISK}/appupgrade -type f 2>/dev/null`"
    fi
    if [ -d ${RAMDISK}/admin/tmp ]; then
        file_pool="${file_pool} `find ${RAMDISK}/admin/tmp -type f 2>/dev/null`"
    fi
    if [ -d ${RAMDISK}/tmp/web_download ]; then
        file_pool="${file_pool} `find ${RAMDISK}/tmp/web_download -type f 2>/dev/null`"
    fi

    for obj in `ls /usr/ramdisk/etc/webuser/ | grep -vE *.json`
    do
        [ ${#obj} -ge 32 ] && continue
        file_pool="${file_pool} /usr/ramdisk/etc/webuser/${obj}"
    done

    for obj in `ls ${PGPATH}/etc/webuser/ | grep -vE *.json`
    do
        [ ${#obj} -ge 32 ] && continue
        file_pool="${file_pool} ${PGPATH}/etc/webuser/${obj}"
    done

    for file in ${file_pool}
    do
        [ ! -f ${file} ] && continue
        size=`ls -l ${file} | awk '{print $5}'`
        total_size=$((${total_size} + ${size}))
        printf ",{\"name\":\"${file}\",\"size\":${size}}"  >> ${tmp_file}
        rm -rf ${file}
    done

    printf "],\"size\":${total_size}}" >> ${tmp_file}
    mv ${tmp_file} ${api_file}
}


disk_usage_check()
{
    api_file="${APIDIR}/disk_${SYS_TIME}.ok"
    tmp_file="${api_file}.tmp"

    df -h | awk -v tmp_file=${tmp_file} \
    'BEGIN{
        dot = "";
        errfind=0;
        printf "{\"type\":\"disk_usage\",\"value\":[" > tmp_file;
    }{
        if(NR == 1) next;
        if($6 == "/dev") next;
        if($6 == "/rom") next;

        split($5, u, "%")
        if(u[1] >= 90) errfind += 1;

        printf "%s{", dot >> tmp_file;
        printf "\"zone\":\"%s\"", $6 >> tmp_file;
        printf ",\"total\":\"%s\"",  $2 >> tmp_file;
        printf ",\"usage\":%s", u[1] >> tmp_file;
        printf "}" >> tmp_file;

        if(dot == "") dot = ",";
    }END{
        printf "],\"errfind\":%s}", errfind >> tmp_file;
    }'
    
    mv ${tmp_file} ${api_file}
}


check_if_miss()
{
    dot=""
    log_file="${LOGDIR}/if_check.log"	
    cur_file="${log_file}.tmp"

    api_file="${APIDIR}/if_${SYS_TIME}.ok"
    tmp_file="${api_file}.tmp"

    # recode to history
    [ -f ${cur_file} ] && rm -rf ${cur_file}
    printf "{\"time\":`date +%s`,\"data\":[" > ${cur_file}

	for x in `${FLOWEYE} if list | cut -d" " -f1`
	do
        crc=`${FLOWEYE}  if stat $x | grep -E "^Crc|^crc" | awk '{print $NF}'`
		miss=`${FLOWEYE} if stat $x | grep -E "^Missed|^ipkts_dropped" | awk '{print $NF}'`
		buff=`${FLOWEYE} if stat $x | grep -E "uffers" | awk '{print $NF}'`

        [ "${crc}"  = "" ] && crc=0
        [ "${miss}" = "" ] && miss=0
        [ "${buff}" = "" ] && buff=0

        printf "${dot}{" >> ${cur_file}
        printf "\"if_name\":\"${x}\"," >> ${cur_file}
        printf "\"crc_err\":${crc}," >> ${cur_file} 
        printf "\"misspkt\":${miss}," >> ${cur_file}
        printf "\"buff\":${buff}" >> ${cur_file}
        printf "}" >> ${cur_file}

		[ "${dot}" = "" ] && dot=","
	done

    printf "]}" >> ${cur_file}
	
    # output to web api
    printf "{\"type\":\"if_miss\",\"cur\":" > ${tmp_file}
    cat ${cur_file} >> ${tmp_file}

    printf ",\"history\":" >> ${tmp_file}

    if [ -f ${log_file} ]; then
        cat ${log_file} >> ${tmp_file}
    else
        printf "{\"time\":0,\"data\":[]}" >> ${tmp_file}
    fi

    printf "}" >> ${tmp_file}

    mv ${cur_file} ${log_file}
    mv ${tmp_file} ${api_file}
}


check_user_login()
{
    api_file="${APIDIR}/zlogin_${SYS_TIME}.ok"
    tmp_file="${api_file}.tmp"

    iplist=""
    dot=""

    for log_file in `find ${DATAPATH} -name "web_*.log" -type f -mtime -30`
    do
        for ip in `grep "û¼"  ${log_file} | cut -d" " -f2`
        do
            key=`echo ${ip} |  sed 's/\./_/g'`
            exist=`echo "${iplist}" | grep " ${ip} "`
			
            if [ "${exist}" = "" ]; then
                iplist=" ${iplist} ${ip} "
                cnt=1
            else
                eval cnt=\$ip${key}
                cnt=$((${cnt}+1))
            fi

            eval ip${key}=$cnt

            [ "${dot}" = "" ]&& dot="," 
        done
    done

    dot=""
    echo -n "{\"type\":\"zlogin\",\"value\":["  > ${tmp_file}

    for ip in ${iplist}
    do
        key=`echo ${ip} | sed 's/\./_/g'`
        eval cnt=\$ip${key}

        printf "${dot}{"  >> ${tmp_file}
        printf "\"times\":${cnt},\"ip\":\"${ip}\"" >> ${tmp_file}
        printf "}"  >> ${tmp_file}

        [ "${dot}" = "" ] && dot="," 
    done

    echo -n  "]}" >> ${tmp_file}
    mv ${tmp_file} ${api_file}
}


check_sockstat()
{
    api_file="${APIDIR}/sockstat_${SYS_TIME}.ok"
    tmp_file="${api_file}.tmp"

    awk -v tmp_file=${tmp_file} \
    'BEGIN{
        dot="";
        printf "{\"type\":\"sockstat\",\"value\":[" > tmp_file;
    }{
        printf "%s\"%s\"",dot,$0 >> tmp_file;
        if(dot=="") dot=",";
    }END{
        printf "]}" >> tmp_file
    }' << EOF
` [ "${SYS_OS}" = "Linux" ] && ss -f inet -a || sockstat -4 `
EOF

    mv ${tmp_file} ${api_file}
}


check_modify_file()
{
    api_file="${APIDIR}/modify_${SYS_TIME}.ok"
    tmp_file="${api_file}.tmp"

    dot=""
    errfind=0
    system_file="${system_file} /sbin/ipe_help /etc/dropbear/dropbear_ecdsa_host_key"
    system_file="${system_file} /etc/resolv.conf /etc/motd /var/tmp/random-seed /etc/PG.conf"
    system_file="${system_file} /root/.ssh/known_hosts /root/.history /root/.viminfo"

    echo -n "{\"type\":\"modify\",\"value\":["  >> ${tmp_file}

    for file in `find / -type f -mtime -30 2> /dev/null | grep -v -E "(\/usr\/ramdisk|\/usr\/system|\/usr\/panabit|\/usr\/panalog|\/usr\/panaetc|msgpipe|\/proc|\/sys|\/run|\/conf|\/log|\/usr/share/|\/data|\/ntmlog|\/userdata|\/rom)"`
    do
        [ "${file}" = "" ] && continue
        exist=`echo " ${system_file} " | grep " ${file} "`
        [ "${exist}" != "" ] && continue
        errfind=$((${errfind} + 1))
        
        printf "${dot}\"${file}\"" >> ${tmp_file}
        [ "${dot}" = "" ] && dot=","
    done
    printf "]}" >> ${tmp_file}

    mv ${tmp_file} ${api_file}
}


main()
{
    SYS_OS=`uname`
    SYS_TIME=`date +%s`

    mkdir -p ${LOGDIR}
    mkdir -p ${APIDIR}
    rm -rf ${TMPDIR}/api/*

    sys_base_check
    sys_process_check
    disk_auto_clear
    disk_usage_check
    check_if_miss
    check_sockstat
    check_modify_file
    check_user_login
}

main
