#!/bin/sh

. /etc/PG.conf

MALCDIR="${DATAPATH}/pamalc"
FLOWEYE="/usr/ramdisk/bin/floweye"
DOWNLOAD="/usr/ramdisk/bin/download"
SYNC_TIME="/conf/web/pamalc_sync_time.conf"
SYNC_FLAG="${MALCDIR}/pamalc_today_sync_done"

if [ -f "/usr/pabin/pacu" ]; then
	CURL="/usr/pabin/pacu"
else
	CURL="`which curl | tail -1`"
fi


hms_to_sec()
{
    local hms="$1"

    echo "${hms}" | awk -F:  \
    '{
        printf "%d\n", ($1 * 3600) + ($2 * 60) + $3;
    }'
}


need_sync_check()
{
    local ver_tag="${MALCDIR}/last_version.time"
    local cloud_ver=`${CURL} -sk -t 60 "https://download.panabit.com:9443/json/index.php?r=threat&action=get_version"`

    if [ $? -ne 0 ]; then
        echo 0
        return
    fi

    if [ ! -f ${ver_tag} ]; then
        echo 1
        echo "${cloud_ver}" > ${ver_tag}
        return
    fi

    local_ver=`cat ${ver_tag}`

    if [ "${cloud_ver}" != "" -a ${cloud_ver} -gt ${local_ver} ]; then
        echo 1
        echo "${cloud_ver}" > ${ver_tag}
    else
        echo 0
    fi
}


monitor_malc_db_load()
{
    [ ! -d ${MALCDIR} ] && return

    ${FLOWEYE} malc list | cut -d" " -f1,2,3,4 | while read id name active load
    do
        dbfile="${MALCDIR}/PanabitMALC_${name}.db"

        [ ! -f ${dbfile} ] && continue
        [ "${load}" = "1" ] && continue

        if [ "${active}" = "0" ]; then
            [ -f ${dbfile} ] && rm ${dbfile}
            continue
        fi

        ${FLOWEYE} malc load db=${id} file=${dbfile}
    done
}


# for cgi check
if [ "${1}" = "need_sync_check" ]; then
    need_sync_check
    exit 0
fi

# confirm OEM
OEM=0
is_qax_tintm=`grep "QAX-TINTM " /usr/ramdisk/etc/panabit.inf `
[ "${is_qax_tintm}" != "" ] && OEM=10


mkdir -p ${MALCDIR}
mkdir -p /usr/ramdisk/tmp

while true;
do
    sleep 10
    
    # Ƿִ
    today=`date +%Y-%m-%d`
    today_have_run=0
    if [ -f ${SYNC_FLAG} ]; then
        exist=`grep ${today} ${SYNC_FLAG}`
        [ "${exist}" = "${today}" ] && today_have_run=1
    fi

    # ÿͬһ
    if [ ${today_have_run} = "0" ]; then

        # ȡʱ뵱ǰʱ䣨HH:MM:SS
        target_time=`cat "${SYNC_TIME}"`
        now_time=`date +%H:%M:%S`

        # תΪ 0 
        now_sec=`hms_to_sec "$now_time"`
        target_sec=`hms_to_sec "$target_time"`

        # ִ
        if [ ${now_sec} -ge ${target_sec} ] && [ $((now_sec - target_sec)) -lt 1800 ]; then
            need_sync=`need_sync_check`
            ${DOWNLOAD} "${OEM}" "${need_sync}"
            echo "$today" > "${SYNC_FLAG}"
        fi
    fi

    # 鱨ؼ
    monitor_malc_db_load
done
