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()

idx = tonumber(cgi.get.idx) or tonumber(cgi.post.idx) or "new"

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

conf = command.ex("cat "..network_conf.dhcpd_conf)
if (conf == nil) then conf = "" end

if (idx == "new") then
    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 - Add New DHCP Subnet</h1></center>
                        </div>
                    </div>
]]
else
    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 - Edit DHCP Subnet</h1></center>
                        </div>
                    </div>
]]
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.<br><br>
                        <a href="network_dhcp.lua">Back to DHCP Server</a>
                    </center>
                </div>
]]
    print(header..content..footer)
    return
else    
    loadValues(conf)
    if (idx ~= "new") and (tonumber(idx) > #(subnets)) then
        -- Bail on error
        content = content .. [[
                <div id="info">
                    <center>
                        <h2><img src="images/warning.png"/> Invalid index</h2>
                        The specified subnet index does not match one of the available subnets.<br><br>
                        <a href="network_dhcp.lua">Back to DHCP Server</a>
                    </center>
                </div>
]]
        print(header..content..footer)
        return        
    end
end

if (cgi.post.submitButton == "Save and Apply") and (userLevel ~= 1) then
    idx = tonumber(cgi.post.idx) or "new"
    
    new_domainName = domainName or ""
    new_domainNameServers = domainNameServers or ""
    
    new_subnet = cgi.post.subnet or ""
    new_netmask = cgi.post.netmask or ""
    new_routers = cgi.post.routerIP or ""
    new_range1 = cgi.post.range1 or ""
    new_range2 = cgi.post.range2 or ""
    
    --if (new_dhcpdArgs ~= "") and (new_domainName ~= "") and (new_domainNameServers ~= "") then
    if (1 == 1) then -- Above line might not be a good idea for editing specific subnets
        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
            if (idx == i) then
                newConf = newConf .. [[
subnet ]]..new_subnet..[[ netmask ]]..new_netmask..[[ {
    option routers ]]..new_routers..[[;
    range ]]..new_range1..[[ ]]..new_range2..[[;
}

]]
            else
                newConf = newConf .. [[
subnet ]]..s.subnet..[[ netmask ]]..s.netmask..[[ {
    option routers ]]..s.routers..[[;
    range ]]..s.range1..[[ ]]..s.range2..[[;
}

]]
            end
        end
        
        if (idx == "new") then
                newConf = newConf .. [[
subnet ]]..new_subnet..[[ netmask ]]..new_netmask..[[ {
    option routers ]]..new_routers..[[;
    range ]]..new_range1..[[ ]]..new_range2..[[;
}

]]
            idx = #(subnets) + 1
        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


if (cgi.post.deleteButton == "Delete Subnet") and (userLevel ~= 1) then
    idx = tonumber(cgi.post.idx) or "new"
    
    newConf = [[
### ]]..network_conf.dhcpd_conf..[[ generated by webconfig

option domain-name "]]..domainName..[[";
option domain-name-servers ]]..domainNameServers..[[;

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

]]

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

]]
        end
    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)
    -- Return
    content = content .. [[
                    <div id="info">
                        <center>
                            <h2>Subnet Deleted</h2>
                            <b>The specified subnet has been deleted.<br><br>
                            <a href="network_dhcp.lua">Back to DHCP server</a>
                        </center>
                    </div>
]]
    print(header..content..footer)
    os.exit()
end



content = content .. [[
    
                    <script language="Javascript" type="text/javascript">
                    
                        var doValidate = 0;
                    
                        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 checkIPs()
                        {
                            var area = document.getElementById("subnetIPs");
                            var inputs = area.getElementsByTagName("input");
                            var loop;
                            var errors = 0;
                            for (loop = 0; loop < inputs.length; loop++)
                            {
                                var warn = document.getElementById("invalidIP_"+loop);
                                if (warn)
                                {
                                    warn.parentNode.removeChild(warn);
                                }
                                
                                if (!ValidateIPaddress(inputs[loop].value))
                                {
                                    var warn = document.createElement("span");
                                    warn.id = "invalidIP_"+loop;
                                    warn.innerHTML = " <img src='images/warning.png' alt='Invalid IP' title='Invalid IP'/> Invalid IP";
                                    inputs[loop].parentNode.appendChild(warn);
                                    errors++;
                                }
                            }
                            return errors;
                        }
   
                        function ValidateForm(form)
                        {
                            if (!doValidate)
                            {
                                form.setAttribute('submitted','true');
                                return true;
                            }
                            doValidate = 0;
                            
                            if (form.getAttribute('submitted')) return false;
                            
                            if (checkIPs())
                            {
                                alert("You have entered one or more invalid IP addresses.\nPlease fix the indicated addresses.");
                                return false;
                            }
                            
                            form.setAttribute('submitted','true');
                        }
                    
                    </script>
    
                    <div class="formLayoutfull">
                        <form action="network_dhcp_edit.lua" method="post" onsubmit="return ValidateForm(this);">
]]

    if (idx == "new") then
        content = content .. [[
                            <h3>New subnet settings</h3>
                            <ul id="subnetIPs">
                                <li><label style="display: inline-block; width: 200px;">Subnet address: </label> <input type="text" name="subnet" value=""]]..inputControl..[[/></li>
                                <li><label style="display: inline-block; width: 200px;">Netmask: </label> <input type="text" name="netmask" value=""]]..inputControl..[[/></li>
                                <li><label style="display: inline-block; width: 200px;">Router address: </label> <input type="text" name="routerIP" value=""]]..inputControl..[[/></li>
                                <li><label style="display: inline-block; width: 200px;">Starting address: </label> <input type="text" name="range1" value=""]]..inputControl..[[/></li>
                                <li><label style="display: inline-block; width: 200px;">Ending address: </label> <input type="text" name="range2" value=""]]..inputControl..[[/></li>
                            </ul>
                            <br>
                            <hr>
                            <br>
]]
    else 
        content = content .. [[
                            <h3>Subnet ]]..idx..[[ settings</h3>
                            <ul id="subnetIPs">
                                <li><label style="display: inline-block; width: 200px;">Subnet address: </label> <input type="text" name="subnet" value="]]..subnets[idx].subnet..[["]]..inputControl..[[/></li>
                                <li><label style="display: inline-block; width: 200px;">Netmask: </label> <input type="text" name="netmask" value="]]..subnets[idx].netmask..[["]]..inputControl..[[/></li>
                                <li><label style="display: inline-block; width: 200px;">Router address: </label> <input type="text" name="routerIP" value="]]..subnets[idx].routers..[["]]..inputControl..[[/></li>
                                <li><label style="display: inline-block; width: 200px;">Starting address: </label> <input type="text" name="range1" value="]]..subnets[idx].range1..[["]]..inputControl..[[/></li>
                                <li><label style="display: inline-block; width: 200px;">Ending address: </label> <input type="text" name="range2" value="]]..subnets[idx].range2..[["]]..inputControl..[[/></li>
                            </ul>
                            <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="hidden" name="idx" value="]]..idx..[["/>
                            <input type="button" name="backButton" value="Back" onclick="window.location.assign('network_dhcp.lua');"/>
                            <input type="submit" name="submitButton" value="Save and Apply"]]..buttonControl..[[ onclick="doValidate = 1;"/>
]]
if (idx ~= "new") then 
    content = content .. [[
                            <input type="submit" name="deleteButton" value="Delete Subnet"]]..buttonControl..[[ onclick="return confirm('Are you sure you want to delete this subnet?');"/>
]]
end
content = content .. [[
                        </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)
