require("luamods/command")
require("luamods/layout")
require("luamods/cgi")
require("config/network_conf")

userLevel = db.getPriv(layout.username) or 1

if (userLevel == 1) then
    buttonControl = " disabled"
    inputControl = " readonly"
    scriptControl = "//"
else
    buttonControl = ""
    inputControl = ""
    scriptControl = ""
end

header = layout.getHeader()
footer = layout.getFooter()

if (cgi.post.submitButton == "Save and Apply") and (userLevel ~= 1) then
    num = 0
    newConf = "### "..network_conf.dns_config.." generated by webconfig\n\n"
    for count = 1,10 do
        if (cgi.post["server"..count] ~= nil) then
            ns = cgi.post["server"..count]
            if (ns ~= nil) and (ns ~= "") then
                num = num + 1
                newConf = newConf .. "nameserver "..ns.."\n"
            end
        end
    end
    search = cgi.post.search or ""
    if (search ~= "") then
        newConf = newConf .. "search "..search.."\n"
    end
    newConf = newConf .. "\n### end of file\n"
    command.writefile(network_conf.dns_config, newConf)
    saved = 1
end

resolv = command.ex("cat "..network_conf.dns_config) or ""

-- This works but I don't know why. Haha oh boy
nameservers = {}
for line in resolv:gmatch("[^\r\n]+") do
    if (line:find("nameserver") ~= nil) then
        entry = line:match("[^#]*"):match("nameserver%s+([^%s]+)")
        if entry ~= nil then
            table.insert(nameservers, entry)
        end
    elseif (line:find("search") ~= nil) then
        search = line:match("[^#]*"):match("search%s+(.+)")
        if search ~= nil then
            searchList = search
        end
    end
end

if searchList == nil then searchList = "" end

content = [[
                    <div id="info">
                        <div style="background:url(images/network.png); background-size:32px; background-repeat:no-repeat; background-position: 20px center;">
                            <center><h1>Network - Domain Name Servers</h1></center>
                        </div>
                    </div>
]]

if (userLevel == 1) then
    content = content .. [[
                    <center><b>Note:</B> Editing this section requires administrator privileges.</center><br>
]]                    
end

if (resolv == nil) then
    -- Bail on error
    content = content .. [[
                    <div id="info">
                        <center>
                            <h2><img src="images/warning.png"/> Cannot read config file</h2>
                            The DNS configuration file "]]..network_conf.dns_config..[[" is missing or unreadable.
                        </center>
                    </div>
]]
    print(header..content..footer)
    return     
else
    content = content .. [[
                    <script language="Javascript" type="text/javascript">
                    
                        function removeField(node,field)
                        {
                            node.parentNode.parentNode.removeChild(node.parentNode);
                            var field_area = document.getElementById(field+"_list");
                            var all_inputs = field_area.getElementsByTagName("input"); //Get all the input fields in the given area.
                            var loop;
                            for (loop = 0; loop < all_inputs.length; loop++)
                            {
                                all_inputs[loop].name = field+(loop+1);
                            }
                        }
                        
                        //Add more fields dynamically.
                        function addField(field, limit)
                        {
                            if (!document.getElementById) return; //Prevent older browsers from getting any further.
                            var field_area = document.getElementById(field+"_list");
                            var all_inputs = field_area.getElementsByTagName("input"); //Get all the input fields in the given area.
                            var count = all_inputs.length;
                            if(count+1 > limit && limit > 0) return;
                            
                            if(document.createElement)
                            { //W3C Dom method.
                                    var li = document.createElement("li");
                                    li.innerHTML = "<input name=\""+(field+(count+1))+"\" style=\"width:300px;\"/><a style=\"cursor:pointer;color:blue;\" onclick=\"removeField(this, '"+field+"');\"> <img src=\"images/trash.png\" alt=\"Delete\" title=\"Delete\"/></a>";
                                    field_area.appendChild(li);
                            }
                            else
                            {       //Older Method
                            }
                        }
                        
                    </script>
                    
                    <div class="formLayoutfull">
                        <form action="network_dns.lua" method="post">
                            <h3>List of domain name servers</h3>
                            <ol id="server_list">
]]
    if (#(nameservers) > 0) then
        for i = 1, #(nameservers)  do
            content = content .. [[
                                <li><input type="text" name="server]]..i..[[" value="]]..nameservers[i]..[[" style="width: 300px;"]]..inputControl..[[/><a style="cursor:pointer;color:blue;" onclick="]]..scriptControl..[[removeField(this, 'server');"> <img src="images/trash.png" alt="Delete" title="Delete"/></a></li>
]]
        end
    end
    content = content .. [[
                            </ol>
                            <input type="button" value="Add Nameserver" onclick="addField('server', 10);"]]..buttonControl..[[/>
                            <br>
                            <br>
                            <hr>
                            <br>
                            <label>Search domain</label><input type="text" name="search" value="]]..searchList..[[" style="width: 300px;"]]..inputControl..[[/>
                            <br>
                            <br>
                            <hr>
                            <br>
]]                            
if (saved == 1) then
    content = content .. [[
                            <b><img src="images/ok.png"/> Changes saved.</b><br><br>
]]
end
content = content .. [[
                            <input type="submit" name="submitButton" value="Save and Apply"]]..buttonControl..[[/>
                        </form>
                    </div>
        
]]
    content = content .. [[
                    <script>
                        function toggleVis(target)
                        {
                            if (target.style.display == "none")
                            {
                                target.style.display = "inline-block";
                            }
                            else
                            {
                                target.style.display = "none";
                            }
                            return false;
                        }
                    </script>
                    <br><img src="images/magnify.png"/> <a href="javascript:void(0)" onclick="toggleVis(document.getElementById('resolv'));">View ]]..network_conf.dns_config..[[</a></a><br>
        
                    <div id="resolv" style="display: none;">
                        <pre class="formLayoutfull">
                        <!-- dns start -->
]]..resolv..[[
                        <!-- dns end -->
                        </pre>
                    </div>
]]  
end

print(header..content..footer)
