#!/bin/sh

. ../common/ajax_common

if [ "${PALANG}" = "en" ]; then
	LANG001="Error"		#ʧ
	LANG002="Success"	#ɹ
	LANG003="Add_IP_Group"	#IPȺ
	LANG004="Set_IP_Group"	#༭IPȺ
	LANG005="Del_IP_Group"	#ɾIPȺ
	LANG006="Del_IP_Group"	#ɾIPȺ
	LANG007="Import_IP_Group"	#IPȺIP
	LANG008="Add_Group_IP"	#IPȺIP
	LANG009="Set_Group_IP"	#༭IPȺIP
	LANG010="Del_Group_IP"	#ɾIPȺIP
	LANG011="Del_Group_IP"	#ɾIPȺIP
fi


list_iptable()
{
    awk \
    'BEGIN{
        dot = "";
        printf "[";
    }{
        if($1 == "") next;

        printf "%s", dot;
        printf "{";
        printf "\"id\":\"%s\",", $1;
        printf "\"name\":\"%s\",", $2;
        printf "\"dnyip\":\"%s\",", $3;
        printf "\"ipnum\":\"%s\"", $4;
        printf "}";
        if (dot == "") dot = ",";
    }END{
        printf "]";
    }' << EOF
`
if [ "${CGI_type}" = "ip" ]; then
    ${FLOWEYE} table get showall=1 allmatched=${CGI_keyword}
else
    ${FLOWEYE} table list showall=1 | grep -i "${CGI_keyword}"
fi
`
EOF
}


add_iptable()
{
    [ "${CGI_name}" = "" ] && retjson 1 "INV_NAME"

    cmdargs="name=${CGI_name}"
    [ "${CGI_dynip}" != "" ] && cmdargs="${cmdargs} dynip=${CGI_dynip}"

    errmsg=`${FLOWEYE} table add ${cmdargs}`

    if [ "$?" != "0" ]; then
        retjson 1 "${LANG001:=ʧ}:${errmsg}"
    else
        sync_floweye "table add ${cmdargs}"
        [ "${NTM}" = "1" ] && ${NTMEYE} table add ${cmdargs}
        WEB_LOGGER "${LANG003:=IPȺ}" " ${cmdargs}"
        retjson 0 "${LANG002:=ɹ}"
    fi
}


set_iptable()
{    
    errmsg=`${FLOWEYE} table set id=${CGI_id} name=${CGI_name}`

    if [ "$?" != "0" ]; then
        retjson 1 "${LANG001:=ʧ}:${errmsg}"
    else
        sync_floweye "table set id=${CGI_id} name=${CGI_name}"
        [ "${NTM}" = "1" ] && ${NTMEYE} table set id=${CGI_id} name=${CGI_name}
        WEB_LOGGER "${LANG004:=༭IPȺ}" "id=${CGI_id} name=${CGI_name}"
        retjson 0 "${LANG002:=ɹ}"
    fi
}


confirm_find_table_in()
{
    grep "^${1}" ${PA_CONF} | awk -v tid=${CGI_id} \
    '{
        pid = "";
        group = "";
        include = 0;

        for(i = 2; i <= NF; i++){
            split($i, item, "=");

            if(item[1] == "group"){
                group = item[2];
                continue;
            }

            if(item[1] == "id"){
                pid = item[2];
                continue;
            }

            if(item[1] != "inip" && item[1] != "outip")
                continue;

            if(item[2] == tid){
                include = 1;
                break;
            }

            split(item[2], val, ",");

            for(x = 1; x <= length(val); x++){
                if(val[x] == tid){
                    include = 1;
                    break;
                }
            }
        }

        if(include == 0)
            printf "";
        else
            printf "%s.%s\n", group, pid;
    }'
}


confirm_build_output()
{
    dot=""
    
    printf "["

    for id in $1
    do
        printf "${dot}\"${id}\""
        [ "${dot}" = "" ] && dot=","
    done

    printf "]"
}


confirm_rmv_info()
{
    export PA_CONF="${PGETC}/panabit.conf"

    #rtp id=20011 app=any src=1 dst=any action=nat-_wg.ABȺ1 nexthop=NULL desc=NULL
    #rtp id=20012 app=any src=any dst=1 action=nat-_wg.ABȺ1 nexthop=NULL desc=NULL
    route=`grep "^rtp " ${PA_CONF} | grep -E "(src|dst).*[,=]+${CGI_id}([[:space:]]|,)" | cut -d" " -f2 | cut -d"=" -f2`
    
    #dnsrule id=100 inip=1 outip=any dns=0 bridge=0 action=pass
    #dnsrule id=5555 inip=any outip=1 dns=0 bridge=0 action=pass
    dnsctl=`grep "^dnsrule " ${PA_CONF} | grep -E "(inip|outip).*[,=]+${CGI_id}([[:space:]]|,)" | cut -d" " -f2 | cut -d"=" -f2`

    #rule group=test id=100 app=any inip=1 dir=both action=permit
    #rule group=test id=2313 app=any outip=1,114.114.114.114 dir=both action=permit
    rule=`confirm_find_table_in "rule"`
    newrule=`confirm_find_table_in "newrule"`

    #clpolicy group=test id=100 inip=1 outip=any maxtcpflow=0 maxudpflow=0 maxflow=0 app=any bridge=0
    #clpolicy group=test id=4444 inip=any outip=1 maxtcpflow=0 maxudpflow=0 maxflow=0 app=any bridge=0
    clpolicy=`grep "^clpolicy " ${PA_CONF} | grep -E "(inip|outip).*[,=]+${CGI_id}([[:space:]]|,)" | awk '{
        split($2, g, "=");
        split($3, p, "=");
        printf "%s.%s\n", g[2], p[2];
    }'`

    #urlpolicy group=test id=123 pool=0 inip=1 dst=any dns=0 ext=0 action=accept method=any
    #urlpolicy group=test id=456 pool=0 inip=any dst=1 dns=0 ext=0 action=accept method=any
    urlpolicy=`grep "^urlpolicy " ${PA_CONF} | grep -E "(inip|outip).*[,=]+${CGI_id}([[:space:]]|,)" | awk '{
        split($2, g, "=");
        split($3, p, "=");
        printf "%s.%s\n", g[2], p[2];
    }'`

    printf "{"
    printf "\"route\":`confirm_build_output \"${route}\"`"
    printf ",\"dnsctl\":`confirm_build_output \"${dnsctl}\"`"
    printf ",\"rule\":`confirm_build_output \"${rule}\"`"
    printf ",\"newrule\":`confirm_build_output \"${newrule}\"`"
    printf ",\"clpolicy\":`confirm_build_output \"${clpolicy}\"`"
    printf ",\"urlpolicy\":`confirm_build_output \"${urlpolicy}\"`"
    printf "}"
}


rmv_iptable()
{
    errmsg=`${FLOWEYE} table remove id=${CGI_id}`

    if [ "$?" != "0" ]; then
        retjson 1 "${LANG001:=ʧ}:${errmsg}"
    else
        sync_floweye "table remove id=${CGI_id}"
        [ "${NTM}" = "1" ] && ${NTMEYE} table remove id=${CGI_id}
        WEB_LOGGER "${LANG005:=ɾIPȺ}" "name=${CGI_name}"
        retjson 0 "${LANG002:=ɹ}"
    fi
}


btnrmv_iptable()
{
    for id in `echo ${CGI_items} | tr ";" " "`
    do
        errmsg=`${FLOWEYE} table remove id=${id}`
        [ $? -ne 0 ] && retjson 1 "${LANG001:=ʧ}:${errmsg}"
        sync_floweye "table remove id=${id}"
        [ "${NTM}" = "1" ] && ${NTMEYE} table remove id=${id}
    done

    WEB_LOGGER "${LANG006:=ɾIPȺ}" "ids=${CGI_items}"
    retjson 0 "${LANG002:=ɹ}"
}


list_tabip()
{
    if [ "${CGI_name}" = "" -a "${CGI_keyword}" = "" ]; then
        printf "{\"total\":0,\"data\":[]}"
        exit 0
    fi

    if [ "${CGI_name}" != "" -a "${CGI_id}" = "" ]; then
        CGI_id=`${FLOWEYE} table list | grep " ${CGI_name}$" | cut -d" " -f1`
    fi

    end=$((${CGI_page} * ${CGI_limit}))
    start=$((${end} - ${CGI_limit}))

    awk -v end=${end} -v start=${start} -v name=${CGI_name} -v id=${CGI_id} -v type=${CGI_type} \
    'BEGIN{
        dot = "";
        row = 0;
        printf "{\"data\":[";
    }{
        if($1 == "") next;
        if(type == "ip" && $1 != id) next;
        
        row++;
        if(row > end || row < start) next;
        printf "%s", dot;
        printf "{";
        printf "\"num\":\"%s\",", row;
        printf "\"id\":\"%s\",", (type == "ip" ? $1 : id);
        printf "\"name\":\"%s\",", (type == "ip" ? $2 : name);
        printf "\"ip\":\"%s\",", (type == "ip" ? $3 : $1);
        printf "\"desc\":\"%s\"", (type == "ip" ? $4 : $2);
        printf "}";
        if(dot == "") dot = ",";
    }END{
        printf "],\"total\":\"%s\"}", row;
    }' << EOF
`
if [ "${CGI_type}" = "ip" -a "${CGI_keyword}" != "" ]; then
    ${FLOWEYE} table get ipmatch=${CGI_keyword}
else
    ${FLOWEYE} table get name=${CGI_name} | grep "${CGI_keyword}"
fi
`
EOF
}


add_tabip()
{
    if [ -f "${CGI_file}" ]; then
        mkdir -p ${TMPDIR}
        ttfile="${TMPDIR}/`date +%s`.$$"
        cat ${CGI_file} | tr -ds '\r' '' > ${ttfile}

        errmsg=`${FLOWEYE} table loadfile tid=${CGI_id} file=${ttfile} clear=${CGI_type}`
        [ $? -ne 0 ] && retjson 1 "${LANG001:=ʧ}:${errmsg}"

        [ "${NTM}" = "1" ] && ${NTMEYE} table loadfile tid=${CGI_id} file=${ttfile} clear=${CGI_type}
        WEB_LOGGER "${LANG007:=IPȺIP}" "tabname=${CGI_name} ip=${CGI_ip}"

        rm -rf "${CGI_file}"
        rm -rf "${ttfile}"
    fi

    if [ "${CGI_ip}" != "" ]; then
        errmsg=`${FLOWEYE} table addip ${CGI_id} ${CGI_ip} info=${CGI_desc}`
        [ $? -ne 0 ] && retjson 1 "${LANG001:=ʧ}:${errmsg}"

        sync_floweye "table addip ${CGI_id} ${CGI_ip} info=${CGI_desc}"
        [ "${NTM}" = "1" ] && ${NTMEYE} table addip ${CGI_id} ${CGI_ip} info=${CGI_desc}
        WEB_LOGGER "${LANG008:=IPȺIP}" "tabname=${CGI_name} ip=${CGI_ip} info=${CGI_desc}"
    fi

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


edit_tabip()
{
    # ${FLOWEYE} table rmvip ${CGI_id} ${CGI_ip}
    errmsg=`${FLOWEYE} table addip ${CGI_id} ${CGI_ip} info=${CGI_desc}`

    if [ $? -ne 0 ]; then
        retjson 1 "${LANG001:=ʧ}:${errmsg}"
    else
        sync_floweye "table addip ${CGI_id} ${CGI_ip} info=${CGI_desc}"
        [ "${NTM}" = "1" ] && ${NTMEYE} table addip ${CGI_id} ${CGI_ip} info=${CGI_desc}
        WEB_LOGGER "${LANG009:=༭IPȺIP}" "tabname=${CGI_name} ip=${CGI_ip} info=${CGI_desc}"
        retjson 0 "${LANG002:=ɹ}"
    fi
}


rmv_tabip()
{
    errmsg=`${FLOWEYE} table rmvip ${CGI_id} ${CGI_ip}`

    if [ "$?" != "0" ]; then
        retjson 1 "${LANG001:=ʧ}:${errmsg}"
    else
        sync_floweye "table rmvip ${CGI_id} ${CGI_ip}"
        [ "${NTM}" = "1" ] && ${NTMEYE} table rmvip ${CGI_id} ${CGI_ip}
        WEB_LOGGER "${LANG010:=ɾIPȺIP}" "tabname=${CGI_name} ip=${CGI_ip}"
        retjson 0 "${LANG002:=ɹ}"
    fi
}


btnrmv_tabip()
{
    for line in `echo ${CGI_items} | tr ";" " "`
    do
        id=`echo ${line} | cut -d"=" -f1`
        ip=`echo ${line} | cut -d"=" -f2`
        errmsg=`${FLOWEYE} table rmvip ${id} ${ip}`

        [ $? -ne 0 ] && retjson 1 "${LANG001:=ʧ}:${errmsg}"
        [ "${NTM}" = "1" ] && ${NTMEYE} table rmvip ${id} ${ip}
        sync_floweye "table rmvip ${id} ${ip}"
    done

    WEB_LOGGER "${LANG011:=ɾIPȺIP}"
    retjson 0 "${LANG002:=ɹ}"
}


clear_tabip()
{
    tmp_path="${RAMDISK}/tmp"
    tmp_file="${tmp_path}/iptmp.list"

    mkdir -p ${tmp_path}
    echo "1.1.1.1" > ${tmp_file}

    errmsg=`${FLOWEYE} table loadfile tid=${CGI_id} file=${tmp_file} clear=1`
    [ $? -ne 0 ] && retjson 1 "${LANG001:=ʧ}:${errmsg}"
    ${FLOWEYE} table rmvip ${CGI_id} 1.1.1.1

    if [ "${NTM}" = "1" ]; then
        ${NTMEYE} table loadfile tid=${CGI_id} file=${tmp_file} clear=1
        [ $? -ne 0 ] && retjson 1 "${LANG001:=ʧ}:${errmsg}"
        ${NTMEYE} table rmvip ${CGI_id} 1.1.1.1
    fi

    rm -rf ${tmp_file}
    WEB_LOGGER "IPȺIP" "id=${CGI_id}"
    retjson 0 "ɹ"
}


export_iptab()
{
    file_name="IPGroup_${CGI_name}.conf"
    file_path="${WEB_DOWNLOAD}/${file_name}"

    mkdir -p ${WEB_DOWNLOAD}

    ${FLOWEYE} table get id=${CGI_id} > ${file_path}

    retjson 0 "OK" "{\"file_name\":\"${file_name}\"}"
}


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

    "list_tabip")
        retjson 0 "OK" "`list_tabip`"
        ;;
    
    "add_iptable")
        action_check
        add_iptable
        ;;
    
    "set_iptable")
        action_check
        set_iptable
        ;;

    "confirm_rmv_info")
        retjson 0 "OK" "`confirm_rmv_info`"
        ;;

    "rmv_iptable")
        action_check
        rmv_iptable
        ;;
    
    "btnrmv_iptable")
        action_check
        btnrmv_iptable
        ;;

    "add_tabip")
        action_check
        add_tabip
        ;;

    "edit_tabip")
        action_check
        edit_tabip
        ;;

    "rmv_tabip")
        action_check
        rmv_tabip
        ;;

    "btnrmv_tabip")
        action_check
        btnrmv_tabip
        ;;

    "clear_tabip")
        action_check
        clear_tabip
        ;;

    "export_iptab")
        action_check
        export_iptab
        ;;

    *)
        retjson 1 "UNKNOW_ACTION"
        ;;
esac
