#!/bin/sh

. /etc/PG.conf

CMDARG="${1}"

RAMDISK="/usr/ramdisk"
FLOWEYE="${RAMDISK}/bin/floweye"
MSGPUSH="${RAMDISK}/bin/ipe_msgpush"
PAINF="${RAMDISK}/etc/panabit.inf"
TMPDIR="${RAMDISK}/tmp/sys_new"

SYS_CONF="${PGETC}/web/system_news_check.conf"
DPI_CONF="${PGETC}/web/system_dpi_check.conf"
APP_CONF="${PGETC}/web/system_app_check.conf"

API="https://download.panabit.com:9443"
EVENTFILE="${PGETC}/log/pending_events"
INSTLL_TOOL="${RAMDISK}/app/webui/bin/install_tool"

if [ "`uname -m`" = "aarch64" ]; then
    CURL="/usr/pabin/pacu --connect-timeout 60 -m 120 -s -k"
else
    CURL="`which curl` --connect-timeout 60 -m 120 -s -k"
fi

[ -f ${PAINF} ] && . ${PAINF}


do_md5()
{
    local os=`uname`
    local fp=$1

    if [ "${os}" = "Linux" ]; then
        md5sum $fp | cut -d" " -f1
    elif [ "${os}" = "FreeBSD" ]; then
        md5 $fp | cut -d" " -f4
    fi
}


action_log()
{
    . ${RAMDISK}/admin/cgi-bin/common/ajax_common

    export REMOTE_ADDR="localhost"
    export PANABIT_USER="__SYSTEM__"

    WEB_LOGGER "${1}" "${2}"
}


upable_check()
{
	isax=`${FLOWEYE} cpu stat | grep "hwproduct=AX"`

	for val in `${FLOWEYE} key info`
	do
		eval "L_${val}"
	done
	
	if [ "${L_cantupgrade}" = "1" -a "${isax}" = "" ]; then
		return 1
	else
        return 0
    fi
}


get_sys_news()
{
    . ${SYS_CONF}
    [ "${enable}" = "0" -a "${CMDARG}" = "" ] && return

    is_iptv=`${FLOWEYE} iptv stat | grep enable`
    [ "${is_iptv}" != "" ] && JOS_RELEASE=4

    os=`uname`
    cpu=`uname -m`
    sys_type=""

    # жϲƷ
    product="panabit"

    if [ "${NTM}" = "1" ]; then
        if [ "${OEM}" = "pac" ]; then
            product="PAC"
        else
            product="ntm"
        fi
    fi

    # жϵͳ汾
    if [ "${os}" = "Linux" ]; then
        if [ "${cpu}" = "aarch64" ]; then
            sys_type="ARM"
        elif [ "${cpu}" = "x86_64" ]; then
            sys_type="Linux"
        fi
    else
        bsdver=`uname -r | cut -d"." -f1`
        [ "${bsdver}" = "9" ] && sys_type="FreeBSD9"
    fi

    [ "${sys_type}" = "" ] && return

	URI="${API}/api/${product}_${JOS_RELEASE}_${sys_type}.info"

	mkdir -p ${TMPDIR}
    info_path="${TMPDIR}/system_news.info"
    ${CURL} "${URI}" -o ${info_path}.bak

    if [ -f ${info_path}.bak ]; then
        #Ƿ°汾
        new_ver=`grep "file_name" ${info_path}.bak | cut -d"_" -f4`
        old_ver=`${FLOWEYE} system stat | grep jflow_ipe_version | cut -d"=" -f2 | cut -d"." -f1`

        have_new=0
        if [ ${new_ver} -gt ${old_ver} ]; then
            have_new=1
            if [ "${notice}" = "1" ]; then
                ${MSGPUSH} -s msg_title=Panabit°汾 msg_ctx=ϵͳ⵽°汾ɸ%0aɵ¼豸鿴 weixin_src=1
            fi
        fi

        echo "check_time=`date +%s`" >> ${info_path}.bak
        echo "have_new=${have_new}" >> ${info_path}.bak
        mv ${info_path}.bak ${info_path}
    fi
}


get_dpi_news()
{
    . ${DPI_CONF}
    [ "${enable}" = "0" -a "${CMDARG}" = "" ] && return

    version=`echo ${BUILDREL} | sed 's/(.*)//g'`
    cloud_info="${TMPDIR}/cloud_dpi.info"
    local_info="${TMPDIR}/system_dpi.info"
    
	URI="${API}/api/DPI_${version}.info"

	mkdir -p ${TMPDIR}
    
    ${CURL} "${URI}" -o ${cloud_info}

    file_ok=`grep "cloud_file_time=" ${cloud_info}`
    
    if [ "${file_ok}" = "" ]; then
        echo "check_time=`date +%s`" > ${local_info}
        echo "check_stat=1" >> ${local_info}
        #漰Ӣķ룬codeǰ
        #echo "check_result=ƶӿ쳣" >> ${local_info}
        return
    fi

    . ${cloud_info}
    local_md5=`do_md5 ${RAMDISK}/bin/dpi.so`
    have_new=0

    if [ ${cloud_file_time} -gt ${WEB_BUILD_TIME} -a "${local_md5}" != "${cloud_dpi_md5}" ]; then
        have_new=1
    fi

    echo "check_time=`date +%s`" > ${local_info}
    echo "file_md5=${cloud_file_md5}" >> ${local_info}
    echo "news_type=${cloud_news_type}" >> ${local_info}
    echo "news_info=${cloud_news_info}" >> ${local_info}
    echo "have_new=${have_new}" >> ${local_info}

    [ "${have_new}" = "0" ] && return
    
    if [ "${upgrade}" != "1" -a "${have_new}" != "1" ]; then
        if [ "${have_new}" == "1" -a "${notice}" = "1" ]; then
            ${MSGPUSH} -s msg_title=Panabit msg_ctx=⵽°汾ɸ%0aɵ¼豸鿴 weixin_src=1
        fi
        return
    fi

    upable_check
    if [ $? -ne 0 ]; then
        echo "dpi_check_stat=2" >> ${local_info}
        #echo "check_result=⵽°汾Ȩδڣ޷" >> ${local_info}
        if [ "${notice}" = "1" ]; then
            ${MSGPUSH} -s msg_title=Panabit msg_ctx=⵽°汾ɸ%0aɹ޷ weixin_src=1
        fi
        return
    fi

    mkdir -p  /usr/ramdisk/upgrade/
    rm -rf /usr/ramdisk/upgrade/*

    URL="${API}/json/index.php?r=package&action=download_package&file_md5=${cloud_file_md5}"
    ${CURL} ${URL} -o /usr/ramdisk/upgrade/dpi.pdb

    pdb_md5=`do_md5 /usr/ramdisk/upgrade/dpi.pdb`

    tar zxf /usr/ramdisk/upgrade/dpi.pdb -C /usr/ramdisk/upgrade
    mv /usr/ramdisk/upgrade/panabitdb/* /usr/ramdisk/upgrade
    rm -rf /usr/ramdisk/upgrade/dpi.pdb
    rm -rf /usr/ramdisk/upgrade/panabitdb
    mkdir -p "${PGETC}/log/"
    echo "upgrade_sigdb yes" >> ${EVENTFILE}

    echo "dpi_check_stat=0" >> ${local_info}

    if [ "${notice}" = "1" ]; then
        ${MSGPUSH} -s msg_title=Panabit msg_ctx=⵽°汾ɸ%0aԶ weixin_src=1
    fi

    action_log "Զ" "Զ"
}


get_app_news()
{
    . ${APP_CONF}
    [ "${enable}" = "0" -a "${CMDARG}" = "" ] && return

    app_root="${RAMDISK}/app"
    cloud_app_list="${TMPDIR}/cloud_app_list.info"
    
	URI="${API}/api/panabit_app_upgrade.conf"

	mkdir -p ${TMPDIR}
    
    ${CURL} "${URI}" -o ${cloud_app_list}

    app_have_new=""
    app_upgraded=""
    have_new_num=0
    upgraded_num=0
    
    for app in `ls ${app_root}`
    do
        cloud_info=`grep "app_name=${app} " ${cloud_app_list}`
        [ "${cloud_info}" = "" ] && continue
        
        local_version=`grep "app_version=" ${app_root}/${app}/app.inf | cut -d"=" -f2 | sed 's/"//g'`
        cloud_version=`echo ${cloud_info} | cut -d" " -f3 | cut -d"=" -f2`
        cloud_filemd5=`echo ${cloud_info} | cut -d" " -f4 | cut -d"=" -f2`
        appcname=`echo ${cloud_info} | cut -d" " -f2 | cut -d"=" -f2`

        have_new=`awk \
        -v lv=${local_version} -v cv=${cloud_version} \
        'BEGIN{
            if(lv < cv)
                printf 1;
            else
                printf 0;
        }'`
        
        [ "${have_new}" = "0" ] && continue

        have_new_num=$((${have_new_num} + 1))
        app_have_new="${app_have_new};${app},${appcname}"

        if [ "${upgrade}" = "0" ]; then
            if [ "${notice}" = "1" ]; then
                ${MSGPUSH} -s msg_title="Panabit%20APP" msg_ctx=${appcname}⵽°汾ɸ weixin_src=1
            fi
            continue
        fi

        installroot="${RAMDISK}/appupgrade"
        mkdir -p ${installroot}/${app}

        ${INSTLL_TOOL} download_app ${app} ${appcname} ${cloud_filemd5} >/dev/null 2>&1 &

        if [ "${notice}" = "1" ]; then
            ${MSGPUSH} -s msg_title="Panabit%20APP" msg_ctx=${appcname}Զ weixin_src=1
        fi

        upgraded_num=$((${upgraded_num} + 1))
        app_upgraded="${app_upgraded};${app},${appcname}"
        action_log "Զ" "Զ${appcname}APP"
    done

    info_path="${TMPDIR}/system_app.info"
    echo "check_time=`date +%s`" > ${info_path}
    echo "have_new_num=${have_new_num}" >> ${info_path}
    echo "upgraded_num=${upgraded_num}" >> ${info_path}
    echo "app_have_new=${app_have_new}" >> ${info_path}
    echo "app_upgraded=${app_upgraded}" >> ${info_path}
}


case "${CMDARG}" in
    "get_sys_news")
        get_sys_news
        exit 0
        ;;

    "get_dpi_news")
        get_dpi_news
        exit 0
        ;;

    "get_app_news")
        get_app_news
        exit 0
        ;;
esac


enable_num=0
for conf in ${SYS_CONF} ${DPI_CONF} ${APP_CONF}
do
    [ ! -f "${conf}" ] && continue

    is_enable=`grep enable=1 ${conf}`
    [ "${is_enable}" != "" ] && enable_num=$((${enable_num} + 1))
done

[ "${enable_num}" = "0" ] && exit 0

app_sleeptime=86400
dpi_sleeptime=$((3600 * 12))
sys_sleeptime=$((86400 * 14))

app_lastime=$(( (`date +%s`) - (${app_sleeptime} - 120) ))
dpi_lastime=$(( (`date +%s`) - (${dpi_sleeptime} - 120) ))
sys_lastime=$(( (`date +%s`) - (${sys_sleeptime} - 120) ))

while true
do
    sleep 1

    cur_time=`date +%s`

    left_time=$((${cur_time} - ${sys_lastime}))
    if [ ${left_time} -ge ${sys_sleeptime} ]; then
        sys_lastime="${cur_time}"
        get_sys_news
    fi

    left_time=$((${cur_time} - ${dpi_lastime}))
    if [ ${left_time} -ge ${dpi_sleeptime} ]; then
        dpi_lastime="${cur_time}"
        get_dpi_news
    fi

    left_time=$((${cur_time} - ${app_lastime}))
    if [ ${left_time} -ge ${app_sleeptime} ]; then
        app_lastime="${cur_time}"
        get_app_news
    fi
done
