. /usr/share/libubox/jshn.sh
. /lib/functions.sh


config_apply()
{
    test -z "$1" && return 1
    
	if [ -e "/dev/appfilter" ];then
    	echo "config json str=$1"
    	echo "$1" >/dev/appfilter
	fi
}

clean_rule()
{
    json_init
    echo "clean appfilter rule..."

    json_add_int "op" 3
    json_add_object "data"
    json_str=`json_dump`

    config_apply "$json_str"

    json_cleanup
}

load_rule()
{
    json_init
    json_add_int "op" 1
    json_add_object "data"
    json_add_array "apps"

    for file in `ls /tmp/appfilter/*.class`
    do
	class_name=`echo "$file" | awk -F/ '{print $4}'| awk -F. '{print $1}'`
	config_get appid_list "appfilter" "${class_name}apps"

	if ! test -z "$appid_list";then
	    for appid in $appid_list:
	    do
	        json_add_int "" $appid
	    done
	fi
    done

    json_str=`json_dump`
    config_apply "$json_str"
    json_cleanup
}

load_mac_list()
{
    json_init
    config_load appfilter
    json_add_int "op" 4
    json_add_object "data"
    json_add_array "mac_list"
    config_get mac_list "user" "users"
    echo "mac list=$mac_list"
    if [ x"$mac_list" != x"" ];then    
        for mac in $mac_list:          
        do                             
            json_add_string "" $mac
        done                           
    fi  
    json_str=`json_dump`
    config_apply "$json_str"
    json_cleanup
}

reload_rule(){
    config_load appfilter
    clean_rule
    load_rule
    load_mac_list
}


case $1 in
"reload")
	echo "reload appfilter rule..."
	reload_rule
;;
esac
