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"
else
    buttonControl = ""
    inputControl = ""
end

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

conf = command.ex("cat "..network_conf.dhcpd_conf)
if (conf == nil) then conf = "" 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 - DHCP Server</h1></center>
                        </div>
                    </div>
]]


function loadValues(conf)
    domainName = conf:match('option%s+domain%-name%s+%"?(.-)%"?;') or ""
    domainNameServers = conf:match('option%s+domain%-name%-servers%s+%"?(.-)%"?;') or ""
    
    subnets = {}
    for subnetConf in conf:gmatch("%s-(subnet%s-.-})%s-") do
        subnet = {}
        subnet.subnet = subnetConf:match('subnet%s-(%d+%.%d+%.%d+%.%d+)') or ""
        subnet.netmask = subnetConf:match('netmask%s-(%d+%.%d+%.%d+%.%d+)') or ""
        subnet.routers = subnetConf:match("option%s+routers%s+(%d+%.%d+%.%d+%.%d+);") or ""
        subnet.range1 = subnetConf:match("range%s+(%d+%.%d+%.%d+%.%d+)%s+%d+%.%d+%.%d+%.%d+;") or ""
        subnet.range2 = subnetConf:match("range%s+%d+%.%d+%.%d+%.%d+%s+(%d+%.%d+%.%d+%.%d+);") or ""
        table.insert(subnets, subnet)
    end    
end

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

if (conf == "") then
    -- Bail on error
    content = content .. [[
                <div id="info">
                    <center>
                        <h2><img src="images/warning.png"/> Cannot read config file</h2>
                        Either the DHCP server (daemon) has not been installed, or its<br>
                        config file "]]..network_conf.dhcpd_conf..[[" is missing or unreadable.
                    </center>
                </div>
]]
    print(header..content..footer)
    return
else    
    loadValues(conf)
end    

if (cgi.post.submitButton == "Save and Apply") and (userLevel ~= 1) then
    new_domainName = cgi.post.domainName or ""
    new_domainNameServers = cgi.post.domainNameServer or ""
    
    if (new_domainName ~= "") and (new_domainNameServers ~= "") then
        saved = 1
        newConf = [[
### ]]..network_conf.dhcpd_conf..[[ generated by webconfig

option domain-name "]]..new_domainName..[[";
option domain-name-servers ]]..new_domainNameServers..[[;

default-lease-time 14440;
ddns-update-style none;
deny bootp;

]]
        for i,s in pairs(subnets) do
            newConf = newConf .. [[
subnet ]]..s.subnet..[[ netmask ]]..s.netmask..[[ {
    option routers ]]..s.routers..[[;
    range ]]..s.range1..[[ ]]..s.range2..[[;
}

]]
        end

        newConf = newConf .. [[
### end of file
]]
        command.writefile(network_conf.dhcpd_conf, newConf)
        command.ex(network_conf.dhcpd_stop)
        command.ex(network_conf.dhcpd_start)
    end
    conf = command.ex("cat "..network_conf.dhcpd_conf)
    if (conf == "") then
        -- Bail on error
        content = content .. [[
                <div id="info">
                    <center>
                        <h2><img src="images/warning.png"/> Cannot read config file</h2>
                        Either the DHCP server (daemon) has not been installed, or its<br>
                        config file "]]..network_conf.dhcpd_conf..[[" is missing or unreadable.
                    </center>
                </div>
]]
        print(header..content..footer)
        return    
    else
        loadValues(conf)
    end
end
    
content = content .. [[
    
                    <script language="Javascript" type="text/javascript">
                    
                        function ValidateIPaddress(inputText)  
                        {  
                            var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
                            if (inputText.match(ipformat))
                            {  
                                return true;  
                            }  
                            else  
                            {  
                                return false;  
                            }  
                        }                    
                        
                        function checkNonBlanks()
                        {
                            var area = document.getElementById("nonBlanks");
                            var inputs = area.getElementsByTagName("input");
                            var loop;
                            var errors = 0;
                            for (loop = 0; loop < inputs.length; loop++)
                            {
                                var warn = document.getElementById("blank_"+loop);
                                if (warn)
                                {
                                    warn.parentNode.removeChild(warn);
                                }
                                
                                if (inputs[loop].value == "")
                                {
                                    var warn = document.createElement("span");
                                    warn.id = "blank_"+loop;
                                    warn.innerHTML = " <img src='images/warning.png' alt='Blank field' title='Blank field'/> Blank";
                                    inputs[loop].parentNode.appendChild(warn);
                                    errors++;
                                }
                            }
                            return errors;                            
                        }
   
                        function ValidateForm(form)
                        {
                            if (form.getAttribute('submitted')) return false;
                            
                            if (checkNonBlanks())
                            {
                                alert("You have left one or more required fields blank.\nPlease fill in the indicated fields.");
                                return false;
                            }
                            
                            form.setAttribute('submitted','true');
                        }
                    
                    </script>
    
                    <div class="formLayoutfull">
                        <form action="network_dhcp.lua" method="post" onsubmit="return ValidateForm(this);">
                            <h3>Global parameters</h3>
                            <ul id="nonBlanks">
                                <li><label style="display: inline-block; width: 200px;">Domain name: </label> <input type="text" name="domainName" value="]]..domainName..[["]]..inputControl..[[/></li>
                                <li><label style="display: inline-block; width: 200px;">Domain name server: </label> <input type="text" name="domainNameServer" value="]]..domainNameServers..[["]]..inputControl..[[/></li>
                            </ul>
                            
]]

if (#(subnets) > 0) then
    content = content .. [[
                            <hr>
                            <h3>Configured subnets:</h3>
                            <table class="onetwo" style="vertical-align: center;">
                                <tr>
                                    <th width="10%">#</th>
                                    <th width="45%">Subnet</th>
                                    <th width="45%">Netmask</th>
                                </tr>
]]        
    for idx,sub in pairs(subnets) do
        content = content .. [[
                                <tr>
                                    <td>]]..idx..[[</td>
                                    <td><a href="network_dhcp_edit.lua?idx=]]..idx..[[">]]..sub.subnet..[[ <img src="images/spanner.png"/></a></td>
                                    <td>]]..sub.netmask..[[</td>
                                </tr>
]]
    end
    content = content .. [[
                            </table><br><hr><br>
]]
else
    content = content .. [[
                            <br><b>Note:</b> There are currently no configured subnets.<br><br><hr><br>
]]        
end

if (saved == 1) then
    content = content .. [[
                            <b><img src="images/ok.png"/> Changes saved.</b><br><br>
]]
end
content = content .. [[
                            <input type="button" name="addButton" value="Add New Subnet"]]..buttonControl..[[ onclick="window.location.assign('network_dhcp_edit.lua?');"/>
                            <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('dhcp'));">View ]]..network_conf.dhcpd_conf..[[</a></a><br>
        
                    <div id="dhcp" style="display: none;">
                        <pre class="formLayoutfull">
                        <!-- dhcpd conf start -->
]]..conf..[[
                        <!-- dhcpd conf end -->
                        </pre>
                    </div>
]]    

print(header..content..footer)
