#!/bin/sh

. ../common/ajax_common


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


load_config_env()
{
    . ../common/ajax_object_lib

    printf "{"
    printf "\"wan\":`lib_proxy_list wan`"
    printf ",\"dns\":`lib_dnsgrp_list`"
    printf ",\"conf\":`load_dnsnat_config`"
    printf "}"
}


set_config_env()
{
    cmdargs="enable=${CGI_dnsnat_enable} dns=${CGI_dnsnat_dnsgrp} pxy=${CGI_dnsnat_pxy}"
    cmdargs="${cmdargs} ipstart=${CGI_dnsnat_ipstart} ipend=${CGI_dnsnat_ipend} ttldelay=${CGI_dnsnat_ttldelay}"
    errmsg=`${FLOWEYE} dnsnat config ${cmdargs}`

    if [ $? -ne 0 ]; then
        retjson 1 "ʧܣ${errmsg}"
    else
        sync_floweye "dnsnat config ${cmdargs}"
        WEB_LOGGER "DNS_NAT" "${cmdargs}"
        retjson 0 "ɹ"
    fi
}


list_dns_nat()
{
    ${FLOWEYE} dnsnat list | grep "${CGI_keyword}" | awk \
    'BEGIN{
        dot = "";
        printf "[";
    }{
        col = 1;

        printf "%s{", dot;
        printf "\"id\":\"%s\"", $(col++);
        printf ",\"host\":\"%s\"", $(col++);
        printf ",\"vir_ip\":\"%s\"", $(col++);
        printf ",\"usr_ip\":\"%s\"", $(col++);
        printf ",\"ttl\":\"%s\"", $(col++);
        printf ",\"ltime\":\"%s\"", $(col++);
        printf ",\"hits\":\"%s\"", $(col++);
        printf ",\"oks\":\"%s\"", $(col++);
        printf "}";
        if(dot == "") dot = ",";
    }END{
        printf "]";
    }'
}


case "${CGI_action}" in

    "load_config_env")
        retjson 0 "OK" "`load_config_env`"
        ;;

    "set_config_env")
        action_check
        set_config_env
        ;;

    "list_dns_nat")
        retjson 0 "OK" "`list_dns_nat`"
        ;;

    *)
        retjson 1 "UNKNOW_ACTION"
        ;;
esac
