#!/bin/sh

. ../common/ajax_common

if [ "${PALANG}" = "en" ]; then
    LANG001="Error"				#ʧ
    LANG002="Success"			#ɹ
fi

if [ "${NTM}" = "1" ]; then
    MAX_PING_NUM=10000
else
    MAX_PING_NUM=512
fi

PING_CONF="${PGETC}/web/pingmonitor.conf"
PING_LIST="${PGETC}/web/pingmonitor.list"

if [ "${NTM}" = "1" ]; then
    WORKDIR="/usr/ntmlog/pingmonitor"
else
    WORKDIR="${RAMDISK}/tmp/pingmonitor"
fi

LOGDIR="${DATAPATH}/App/pingmonitor/"
LOGFILE="${LOGDIR}/error_notice.log"


load_pingmonitor_conf()
{
    if [ ! -f ${PING_CONF} ]; then
        printf "{}"
        return
    fi

    awk -F"=" \
    'BEGIN{
        dot = "";
        printf "{";
    }{
        printf "%s\"%s\":\"%s\"", dot, $1, $2;
        if(dot == "") dot = ",";
    }END{
        printf "}"
    }' ${PING_CONF}
}


set_pingmonitor_conf()
{
    mkdir -p ${PGETC}/web

    echo "ping_enable=${CGI_ping_enable}" > ${PING_CONF}
    echo "ping_sleep=${CGI_ping_sleep}" >> ${PING_CONF}
    echo "ping_max=${CGI_ping_max}" >> ${PING_CONF}
    echo "warring_enable=${CGI_warring_enable}" >> ${PING_CONF}
    echo "warring_object=${CGI_warring_object}" >> ${PING_CONF}
    echo "warring_maxerror=${CGI_warring_maxerror}" >> ${PING_CONF}
    echo "warring_delay=${CGI_warring_delay}" >> ${PING_CONF}
    echo "warring_miss=${CGI_warring_miss}" >> ${PING_CONF}
    echo "notice_type=${CGI_notice_type}" >> ${PING_CONF}
    echo "notice_interval=${CGI_notice_interval}" >> ${PING_CONF}

    ${WEBUICTL} start ping_monitor >/dev/null 2>&1 &

    WEB_LOGGER "Ping"
 	retjson 0 "${LANG002:=ɹ}"
}


load_addobj_env()
{
    . ${PGETC}/ifadmin.conf
    
    printf "{\"mgtip\":\"${ADMIN_IP}\""
    printf ",\"proxy\":["

    ${FLOWEYE} nat listproxy json=1
    
    printf "]}"
}


add_pingmonitor_obj()
{
    index=0
    cur_time=`date +%s`

    mkdir -p ${PGETC}/web/
    touch ${PING_LIST}

    for pxy in ${CGI_pxy}
    do
        index=$((${index} + 1))
        id="${cur_time}${index}"

        rows=`awk 'END{print NR}' ${PING_LIST}`
        [ ${rows} -ge ${MAX_PING_NUM} ] && retjson 1 "ʧܣƣ${MAX_PING_NUM}"
        echo "id=${id} pxy_id=${pxy} obj=${CGI_obj} nexthop=${CGI_nexthop} desc=${CGI_desc} warring=${CGI_warring}" >> ${PING_LIST}
    done

    ${WEBUICTL} start ping_monitor >/dev/null 2>&1 &

    WEB_LOGGER "Ping"
	retjson 0 "${LANG002:=ɹ}"
}


import_pingmonitor_obj()
{
    [ ! -f ${CGI_file} ] && retjson 1 "INV_FILE"

    index=0
    cur_time=`date +%s`

    cat ${CGI_file} | tr -ds '\r' '' | while read ip desc nexthop
    do
        index=$((${index} + 1))
        id="${cur_time}${index}"

        rows=`awk 'END{print NR}' ${PING_LIST}`
        [ ${rows} -ge ${MAX_PING_NUM} ] && retjson 1 "ʧܣƣ${MAX_PING_NUM}"
        echo "id=${id} pxy_id=${CGI_pxy_id} obj=${ip} nexthop=${nexthop} desc=${desc} warring=0" >> ${PING_LIST}
    done

    ${WEBUICTL} start ping_monitor >/dev/null 2>&1 &
    
    WEB_LOGGER "Ping"
	retjson 0 "${LANG002:=ɹ}"
}


edit_pingmonitor_obj()
{
    [ "${CGI_id}" = "" ] && retjson 1 "INV_ID"

    grep -v "^id=${CGI_id} " ${PING_LIST} > ${PING_LIST}.bak

    echo "id=${CGI_id} pxy_id=${CGI_pxy_id} obj=${CGI_obj} nexthop=${CGI_nexthop} desc=${CGI_desc} warring=${CGI_warring}" >> ${PING_LIST}.bak
    mv ${PING_LIST}.bak ${PING_LIST}

    ${WEBUICTL} start ping_monitor >/dev/null 2>&1 &

    WEB_LOGGER "༭Ping"
	retjson 0 "${LANG002:=ɹ}"
}


list_pingmonitor_obj()
{
    if [ ! -f ${PING_LIST} ]; then
        printf "[]"
        return
    fi

    grep -i "${CGI_keyword}" ${PING_LIST} | awk \
    'BEGIN{
        dot = "";
        printf "[";
    }{
        printf "%s{", dot;

        d = "";
        
        for(i = 1; i <= NF; i++){
            split($i, val, "=");
            printf "%s\"%s\":\"%s\"", d, val[1], val[2];
            if(d == "") d = ",";
        }

        printf "}";
        if(dot == "") dot = ",";
    }END{
        printf "]";
    }'
}


get_proxy_dict()
{
    ${FLOWEYE} nat listproxy | awk \
    'BEGIN{
        dot = "";
        printf "{";
    }{
        printf "%s\"pxy_%s\":\"%s\"", dot, $2, $3;
        if(dot == "") dot = ",";
    }END{
        printf "}";  
    }'
}


load_pingmonitor_stat()
{
    ping_data_file="${WORKDIR}/ping_data.json"
    ping_time_file="${WORKDIR}/ping_time.json"

    printf "{"
    printf "\"conf\":`list_pingmonitor_obj`"
    printf ",\"pxy\":`get_proxy_dict`"

    if [ -f ${ping_data_file} ]; then
        printf ",\"stat\":"
        cat ${ping_data_file}
    fi

    if [ -f ${ping_time_file} ]; then
        printf ",\"time\":"
        cat ${ping_time_file}
    fi

    in_runing="`ps -ax | grep pa_pingmonitor | grep -v grep`"

    if [ "${in_runing}" = "" ]; then
        printf ",\"runing\":\"no\""
    else
        printf ",\"running\":\"yes\""
    fi

    printf "}"
}


rmv_pingmonitor_obj()
{
    grep -v "id=${CGI_id} " ${PING_LIST} > ${PING_LIST}.bak
    mv ${PING_LIST}.bak ${PING_LIST}

    ${WEBUICTL} start ping_monitor >/dev/null 2>&1 &

    WEB_LOGGER "ɾPing"
	retjson 0 "${LANG002:=ɹ}"
}


btnrmv_pingmonitor_obj()
{
    for id in ${CGI_items}
    do
        grep -v "id=${id} " ${PING_LIST} > ${PING_LIST}.bak
        mv ${PING_LIST}.bak ${PING_LIST}
    done

    ${WEBUICTL} start ping_monitor >/dev/null 2>&1 &

    WEB_LOGGER "ɾPing"
	retjson 0 "${LANG002:=ɹ}"
}


clear_pingmonitor_obj()
{
    [ -f ${PING_LIST} ] && rm -rf ${PING_LIST}

    ${WEBUICTL} start ping_monitor >/dev/null 2>&1 &

    WEB_LOGGER "Pingб"
    retjson 0 "${LANG002:=ɹ}"
}


load_notice_log()
{
    if [ ! -f ${LOGFILE} ]; then
        printf "[]"
        return
    fi

    grep -i "${CGI_keyword}" ${LOGFILE} | awk -F"," \
    'BEGIN{
        dot = "";
        printf "[";
    }{
        gsub("%0a", "", $4);
        gsub("%20", " ", $4);

        col = 1;
        printf "%s{", dot;
        printf "\"time\":\"%s\"", $1;
        printf ",\"int\":\"%s\"", $2;
        printf ",\"obj\":\"%s\"", $3;
        printf ",\"ctx\":\"%s\"", $4;
        printf ",\"times\":\"%s\"", $5;
        printf "}";
        if(dot == "") dot = ",";
    }END{
        printf "]";
    }'
}


clear_ping_alert_log()
{
    if [ -f ${LOGFILE} ]; then
        printf "" > ${LOGFILE}
    fi

    WEB_LOGGER "Ping澯־"
    retjson 0 "ɹ"
}


export_ping_alert_log()
{
    file_name="Ping澯־.csv"
    file_path="${WEB_DOWNLOAD}/${file_name}"

    mkdir -p ${WEB_DOWNLOAD}

    echo "ʱ,Pingӿ,Ping,澯" > ${file_path}

    if [ -f ${LOGFILE} ]; then
        awk -F"," \
        '{
            gsub("%0a", "", $0);
            gsub("%20", " ", $0);

            printf "%s,%s,%s,%s\n", $5, $2, $3, $4;
        }' ${LOGFILE} >> ${file_path}
    fi
    
    retjson 0 "OK" "{\"file_name\":\"${file_name}\"}"
}


case "${CGI_action}" in
    "load_pingmonitor_conf")
        retjson 0 "OK" "`load_pingmonitor_conf`"
        ;;

    "set_pingmonitor_conf")
        action_check
        set_pingmonitor_conf
        ;;

    "load_addobj_env")
        retjson 0 "OK" "`load_addobj_env`"
        ;;

    "add_pingmonitor_obj")
        action_check
        add_pingmonitor_obj
        ;;

    "import_pingmonitor_obj")
        action_check
        import_pingmonitor_obj
        ;;

    "edit_pingmonitor_obj")
        action_check
        edit_pingmonitor_obj
        ;;

    "load_pingmonitor_stat")
        retjson 0 "OK" "`load_pingmonitor_stat`"
        ;;

    "rmv_pingmonitor_obj")
        action_check
        rmv_pingmonitor_obj
        ;;

    "btnrmv_pingmonitor_obj")
        action_check
        btnrmv_pingmonitor_obj
        ;;

    "clear_pingmonitor_obj")
        action_check
        clear_pingmonitor_obj
        ;;

    "load_notice_log")
        retjson 0 "OK" "`load_notice_log`"
        ;;

    "clear_ping_alert_log")
        action_check
        clear_ping_alert_log
        ;;

    "export_ping_alert_log")
        action_check
        export_ping_alert_log
        ;;

    *)
        retjson 1 "UNKNOW_ACTION"
        ;;
esac
