#!/bin/sh

. ../common/ajax_common

if [ "${PALANG}" = "en" ]; then
	LANG001="Error"		#ʧ
	LANG002="Success"	#ɹ
	LANG003="Add_IP_Group"	#˺Ⱥ
	LANG004="Set_IP_Group"	#༭˺Ⱥ
	LANG005="Del_IP_Group"	#ɾ˺Ⱥ
	LANG006="Del_IP_Group"	#ɾ˺Ⱥ
	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_usertable()
{
    ${NTMEYE} ntmusergrp list keywd=${CGI_keyword} | awk '
    BEGIN{
        dot = "";
        printf "[";
    }{
        if($1 == "") next;

        printf "%s", dot;
        printf "{";
        printf "\"id\":\"%s\",", $1;
        printf "\"usernum\":\"%s\",", $2;
        printf "\"name\":\"%s\"", $3;

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


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

    errmsg=`${NTMEYE} ntmusergrp add grpname=${CGI_name}`

    if [ "$?" != "0" ]; then
        retjson 1 "${LANG001:=ʧ}:${errmsg}"
    else
        retjson 0 "${LANG002:=ɹ}"
    fi
}


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

    errmsg=`${NTMEYE} ntmusergrp set gid=${CGI_id} grpname=${CGI_name}`

    if [ "$?" != "0" ]; then
        retjson 1 "${LANG001:=ʧ}:${errmsg}"
    else
        retjson 0 "${LANG002:=ɹ}"
    fi  
}


confirm_find_policy()
{
    grep "^${1}" ${PGETC}/panabit.conf | awk -v tid=${CGI_id} -v obj=$2 \
    'BEGIN{
        dot = "";
        printf "[";

        split(obj, objs, ",");
        for(i = 1; i <= length(objs); i++)
            keys[objs[i]] = i;
    }{
        group = "";
        pid = "";
        include = 0;
        
        for(i = 2; i <= NF; i++){
            
            split($i, item, "=");
            
            # ȡءơHTTPܿصĲ
            if(item[1] == "group"){
                group = item[2];
                continue;
            }

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

            # жKEYǷ
            if (!(item[1] in keys))
                continue;

            # ϰ汾IPֻһ
            if(item[2] == tid){
                include = 1;
                break;
            }
            
            # °汾IP˶
            split(item[2], val, ",");
            for(x = 1; x <= length(val); x++){
                split(val[x], cfg, ":"); #ƥ tid:˿ 
                if(cfg[1] == tid){
                    include = 1;
                    break;
                }
            }
        }

        if(include == 0)
            next;

        if(group != "")
            printf "%s\"%s.%s\"", dot, group, pid;
        else
            printf "%s\"%s\"", dot, pid;

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


confirm_rmv_info()
{
    #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=`confirm_find_policy "rtp" "src,dst"`
    
    #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=`confirm_find_policy "dnsrule" "inip,outip"`

    #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_policy "rule" "inip,outip"`
    newrule=`confirm_find_policy "newrule" "inip,outip"`

    #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=`confirm_find_policy "clpolicy" "inip,outip"`

    #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=`confirm_find_policy "urlpolicy" "inip,dst"`

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


btnrmv_usertable()
{
    for id in `echo ${CGI_items} | tr ";" " "`
    do
        ${NTMEYE} ntmusergrp remove gid=${id}
    done

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


list_tabuser()
{
    if [ "${CGI_name}" = "" -a "${CGI_keyword}" = "" ]; then
        printf "{\"total\":0,\"data\":[]}"
        exit 0
    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} \
    'BEGIN{
        dot = "";
        row = 0;
        printf "{\"data\":[";
    }{
        if($1 == "") next;
        
        row++;
        if(row > end || row < start) next;
        printf "%s", dot;
        printf "{";
        printf "\"id\":\"%s\",", $1;
        printf "\"name\":\"%s\",", name;
        printf "\"user\":\"%s\",", $2;
        printf "\"desc\":\"%s\"", $3;
        printf "}";
        if(dot == "") dot = ",";
    }END{
        printf "],\"total\":\"%s\"}", row;
    }' << EOF

    `
        if [ "${CGI_keyword}" = "" ]; then
            ${NTMEYE} ntmuseritem list gid=${CGI_id}
        else
            ${NTMEYE} ntmuseritem list gid=${CGI_id} user=${CGI_keyword}
        fi
    `
EOF
}


add_tabuser()
{
    [ "${CGI_user}" = "" ] && retjson 1 "INV_user"

    errmsg=`${NTMEYE} ntmuseritem add gid=${CGI_id} user=${CGI_user} extr=${CGI_desc}`

    if [ "$?" != "0" ]; then
        retjson 1 "${LANG001:=ʧ}:${errmsg}"
    else
        retjson 0 "${LANG002:=ɹ}"
    fi
}


edit_tabuser()
{
    [ "${CGI_user}" = "" ] && retjson 1 "INV_user"

    errmsg=`${NTMEYE} ntmuseritem set gid=${CGI_id} user=${CGI_user} extr=${CGI_desc}`

    if [ "$?" != "0" ]; then
        retjson 1 "${LANG001:=ʧ}:${errmsg}"
    else
        retjson 0 "${LANG002:=ɹ}"
    fi
}


btnrmv_tabuser()
{
    for line in `echo ${CGI_items} | tr ";" " "`
    do
        id=`echo ${line} | cut -d"=" -f1`
        user=`echo ${line} | cut -d"=" -f2`
        errmsg=`ntmeye ntmuseritem remove gid=${id} user=${user}`  
    done

    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_usertable")
        retjson 0 "OK" "`list_usertable`"
        ;;

    "add_usertable")
        action_check
        add_usertable
        ;;
    
    "edit_usertable")
        action_check
        edit_usertable
        ;;
    
    "btnrmv_usertable")
        action_check
        btnrmv_usertable
        ;;

    "list_tabuser")
        retjson 0 "OK" "`list_tabuser`"
        ;;

    "add_tabuser")
        action_check
        add_tabuser
        ;;

    "edit_tabuser")
        action_check
        edit_tabuser
        ;;

    "btnrmv_tabuser")
        action_check
        btnrmv_tabuser
        ;;

    "clear_tabip")
        action_check
        clear_tabip
        ;;

    "export_iptab")
        action_check
        export_iptab
        ;;

    *)
        retjson 1 "UNKNOW_ACTION"
        ;;
esac