#!/bin/sh

. ../common/ajax_common

if [ "${PALANG}" = "en" ]; then
	LANG001="Error"		#ʧ
	LANG002="Success"	#ɹ
	LANG003="Set_File_Group"	#ļȺ
	LANG004="Del_File_Group"	#ɾļȺ
	LANG005="Del_File_Group"	#ɾļȺ
fi


load_file_type()
{
    # id name exts theother
    ${FLOWEYE} urlfilter listext | grep -i "${CGI_keyword}" | awk \
    'BEGIN{
        dot = "";
        printf "[";
    }{
        col = 1;
        printf "%s{", dot;
        printf "\"id\":\"%s\",", $(col++);
        printf "\"name\":\"%s\",", $(col++);
        printf "\"exts\":\"%s\"", $(col++);
        printf "}";
        if(dot == "") dot = ",";
    }END{
        printf "]";
    }'
}


add_file_type()
{   
    if [ "${CGI_id}" != "" ]; then
        cmdargs="id=${CGI_id} exts=${CGI_exts}"
    else
        cmdargs="name=${CGI_name} exts=${CGI_exts}"
    fi

    errmsg=`${FLOWEYE} urlfilter setext ${cmdargs}`

    if [ $? -ne 0 ]; then
        retjson 1 "${LANG001:=ʧ}:${errmsg}"
    else
        sync_floweye "urlfilter setext name=${CGI_name} exts=${CGI_exts}"
        WEB_LOGGER "${LANG003:=ļȺ} name=${CGI_name}"
        retjson 0 "${LANG002:=ɹ}"
    fi
}


rmv_file_type()
{
    errmsg=`${FLOWEYE} urlfilter setext id=${CGI_id} name=none`

    if [ $? -ne 0 ]; then
        retjson 1 "${LANG001:=ʧ}:${errmsg}"
    else
        sync_floweye "urlfilter setext id=${CGI_id} name=none"
        WEB_LOGGER "${LANG004:=ɾļȺ}" "id=${CGI_id} name=${CGI_name}"
        retjson 0 "${LANG002:=ɹ}"
    fi
}


btnremove_file_type()
{
    for id in `echo ${CGI_items} | tr ";" " "`
    do
        errmsg=`${FLOWEYE} urlfilter setext id=${id} name=none`
        [ $? -ne 0 ] && retjson 1 "${LANG001:=ʧ}:${errmsg}"
        sync_floweye "urlfilter setext id=${id} name=none"
    done

    WEB_LOGGER "${LANG005:=ɾļȺ}" "ids=${CGI_items}"
	retjson 0 "${LANG002:=ɹ}"
}


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

    "add_file_type"|"edit_file_type")
        action_check
        add_file_type
        ;;

    "rmv_file_type")
        action_check
        rmv_file_type
        ;;

    "btnremove_file_type")
        action_check
        btnremove_file_type
        ;;

    *)
        retjson 1 "UNKNOW_ACTION"
        ;;
esac
