#!/bin/sh

. /etc/PG.conf

MALCDIR="${DATAPATH}/pamalc"
FLOWEYE="/usr/ramdisk/bin/floweye"
DOWNLOAD="/usr/ramdisk/bin/download"
LOGFILE="/usr/ramdisk/tmp/pa_malc_sync.log"
DB_API="https://download.panabit.com:8443/threat"
PANABIT_ID=`${FLOWEYE} key getcookie2`

if [ "`uname -m`" = "aarch64" ]; then
    CURL="/usr/pabin/pacu"
else
    CURL="curl"
fi


one_day=$(( 24 * 60 * 60 ))
cur_time=`date +%s`
last_worktime=$(( ${cur_time} - ${one_day} ))

while true
do
    sleep 10

    # 鱨ͬ
    cur_time=`date +%s`
    left_time=$((${cur_time} - ${last_worktime}))
    need_sync=`${FLOWEYE} malc list | cut -d" " -f7 | grep 1`
    
    if [ ${left_time} -gt ${one_day} -a "${need_sync}" != "" ]; then
        mkdir -p ${MALCDIR}
        rm -rf ${MALCDIR}/*

        last_worktime="${cur_time}"
        
        ${DOWNLOAD}
    fi

    # 鱨ؼ
    if [ -d ${MALCDIR} ]; then
        ${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

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

done
