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

profileTemplate = [[

Description='Virtual LAN 11 on interface eth0'
Interface=dummy
Connection=vlan
After=('wan')
# The variable name is plural, but needs precisely one interface
BindsToInterfaces=eth1
VLANID=99
IP=static
Address=('10.15.3.113/32')
]]

local function msg(m)
  command.ex([[logger "]]..m..[["]])
end

parents={}

function lookup_parents()
   local profile_list = command.ex([[ ls -p ]]..network_conf.netctl_profile_path..[[| grep -v /]])
   for file in profile_list:gmatch("(.-)\n") do
       local cfg = command.ex("cat "..network_conf.netctl_profile_path.."/"..file)
       if cfg:match("Connection=ethernet") then
          table.insert(parents,file)
       end
   end
end

if (cgi.post.submitButton == "Save and Apply") and (userLevel ~= 1) then
    intfName = cgi.post.name or "unknown"
    parentName = cgi.post.parent or nil
    vlanid = cgi.post.vlanid or nil
    saved = 1

elseif (cgi.post.deleteButton == "Delete") and (userLevel ~= 1) then
        msg("Delete Button")
        intfName = cgi.post.name or "unknown"
        vlanid = cgi.post.vlanid
        
        command.ex([[netctl disable ]]..intfName)
        command.ex([[netctl stop ]]..intfName)
        command.ex([[rm ]]..network_conf.netctl_profile_path..[[/]]..intfName)
        
        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 - Interfaces</h1></center>
                        </div>
                    </div>
                    <div id="info">
                        <center>
                            <h2>Profile "]]..intfName..[[" Deleted</h2>
                            <b>The specified vlan profile has been deleted.<br><br>
                            <a href="network_interfaces.lua">Back to Network Interfaces</a>
                        </center>
                    </div>
]]
    print(header..content..footer)
    os.exit(0)
else

    intfName = cgi.get.interface or nil
    parentName = cgi.get.parent or nil
    vlanid = cgi.get.vlanid or nil
end



if intfName and command.file_exists(network_conf.netctl_profile_path.."/"..intfName) then
  msg("Loading profile..")
  currIntf = command.ex("cat "..network_conf.netctl_profile_path.."/"..intfName)
else  
   msg("Using template..")
  currIntf = profileTemplate
end
if parentName then
  parentIntf = command.ex("cat "..network_conf.netctl_profile_path.."/"..parentName) or ""
end     
  
if (currIntf ~= nil) and (intfName ~= nil) then
    --ifconfigResult = command.ex(network_conf.if_config.." "..intfName.." 2>&1") or ""
    interface = {}
     method = currIntf:match("[^#]IP=(.-)\n") or "none"
     interface.name = intfName
     interface.method = method
     address = currIntf:match("[^#]Address=%('(.+)/(.+)'%)\n") or ""
     netmask = "32"
     interface.address = address
     interface.netmask = netmask
     interface.enabled = command.ex("netctl is-enabled "..interface.name):match("(enabled)") or ""
     interface.interface = currIntf:match("[^#]Interface=(.-)\n") or ""
     if vlanid then
         interface.vlanid = vlanid
     else
         interface.vlanid = currIntf:match("[^#]VLANID=(.-)\n")
     end    
     interface.parent = parentName or ""
     interface.vlaninterface = parentIntf:match("[^#]Interface=(.-)\n") or currentIntf:match("[^#]BindsToInterfaces=(.-)\n") or ""
     
    if (saved == 1) then
        interface.address = cgi.post.address or ""
        if (cgi.post.profile == "enabled") then
            newEnabled = "enabled"
        else
            newEnabled = ""
        end
        
       --Rewrite the whole profile in any case
       
       --Write our own description
        currIntf = currIntf:gsub("Description=.-\n","Description='VLAN \""..interface.name.."\" on parent \""..interface.parent.." ("..interface.vlaninterface..")\"'\n") 
        currIntf = currIntf:gsub("Interface=.-\n","Interface="..interface.name.."\n")
        currIntf = currIntf:gsub("After=.-\n","After=('"..interface.parent.."')\n")
        currIntf = currIntf:gsub("BindsToInterfaces=.-\n","BindsToInterfaces="..interface.vlaninterface.."\n")
        currIntf = currIntf:gsub("VLANID=.-\n","VLANID="..interface.vlanid.."\n")
        currIntf = currIntf:gsub("Address=.-\n","Address=('"..interface.address.."/32')\n")
      

     command.writefile(network_conf.netctl_profile_path.."/"..intfName, currIntf)

     if newEnabled ~= interface.enabled then
        if newEnabled == "enabled" then
           command.ex([[netctl enable ]]..intfName)
        else
           command.ex([[netctl disable ]]..intfName)
        end
     end

        interface.enabled = newEnabled
        
        if interface.enabled == "enabled" then
           command.ex([[netctl restart ]]..intfName)
        else
           command.ex([[netctl stop ]]..intfName)
        end
        msg(currIntf)    
    end
    ifconfigResult = currIntf
else
   interface = {}
   interface.vlanid = vlanid
   interface.enabled = "disabled"
   interface.address = ""
   ifconfigResult = ""
end    
    
lookup_parents()

--else
    -- Bail on error here
    --content = [[
    --                <div id="info"><center><H1>Network - Manage Interface</H1></center></div>
    --                <div id="info">
    --                    <center>
    --                        <h2><img src="images/warning.png"/> Cannot load interface details</h2>
    --                        An invalid interface was selected, or the interface has not been marked<br>
    --                        as being configurable in the interfaces file "]]..network_conf.interface_file..[["<br><br>
    --                        <a href="network_interfaces.lua">View network interfaces</a> | <a href="network_status.lua">View network status</a>
    --                    </center>
    --                </div>
--]]
    --html = header..content..footer
    --print(html)
    --return        
--end    

content = ""

content = [[
                    <script>

                        function check(area)
                        {
                            var inputs = area.getElementsByTagName("input");
                            if (!inputs[0].checked || inputs[1].checked)
                            {
                                inputs[2].readOnly = true;
                                inputs[3].readOnly = true;
                                inputs[4].readOnly = true;
                            }
                            else
                            {
                                inputs[2].readOnly = false;
                                inputs[3].readOnly = false;
                                inputs[4].readOnly = false;
                            }
                        }
                        
                        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 ValidateNetmask(inputText)
                        {
                           var num = parseInt(inputText,10)
                           console.log("Check NM")
                           if (!isNaN(num) && num > 0 && num <= 32)
                           {
                              return true
                           }
                           else
                           {
                              return false
                           }
                        }
                        
                        function ValidateForm(form)
                        {
                            if (form.getAttribute('submitted')) return false;
                            var inputs = form.getElementsByTagName("input");
                            var loop;
                            var errors = 0;
                            inputs[2].removeAttribute("invalidIP");
                           
                            var warn = document.getElementById("invalidIP_"+2);
                            if (warn)
                            {
                                warn.parentNode.removeChild(warn);
                            }
                            
                            if ((inputs[2].value != "") && (!ValidateIPaddress(inputs[2].value)) && (!inputs[2].readOnly))
                            {
                               inputs[2].setAttribute("invalidIP","true");
                               errors++;
                            }
                            if (inputs[2].getAttribute("invalidIP") === "true")
                            {
                               var warn = document.createElement("span");
                               warn.id = "invalidIP_"+2;
                               warn.innerHTML = " <img src='images/warning.png' alt='Invalid IP' title='Invalid IP'/>";
                               inputs[2].parentNode.appendChild(warn);
                            }
                            
                             
                           /*
                            for (loop = 2; loop < 5; loop++)
                            {
                                inputs[loop].removeAttribute("invalidIP");
                                var warn = document.getElementById("invalidIP_"+loop);
                                if (warn)
                                {
                                    warn.parentNode.removeChild(warn);
                                }

                                if(loop != 3)
                                {
                                   if ((inputs[loop].value != "") && (!ValidateIPaddress(inputs[loop].value)) && (!inputs[loop].readOnly))
                                   {
                                      //alert("Input " + loop + " has an invalid IP address! " + inputs[loop].value);
                                      inputs[loop].setAttribute("invalidIP","true");
                                      errors++;
                                   }
                                }
                                else if ((inputs[loop].value != "") && !(ValidateNetmask(inputs[loop].value) || ValidateIPaddress(inputs[loop].value)) && (!inputs[loop].readOnly))
                                {
                                      inputs[loop].setAttribute("invalidIP","true");
                                      errors++;
                                }
                                
                                if (inputs[loop].getAttribute("invalidIP") === "true")
                                {
                                    var warn = document.createElement("span");
                                    warn.id = "invalidIP_"+loop;
                                    warn.innerHTML = " <img src='images/warning.png' alt='Invalid IP' title='Invalid IP'/>";
                                    inputs[loop].parentNode.appendChild(warn);
                                }
                            } */
                            if (errors)
                            {
                                alert("You have entered one or more invalid IP addresses.\nPlease fix the indicated addresses.");
                                return false;
                            }
                            else
                            {
                                form.setAttribute('submitted','true');
                                return true;
                            }
                        }

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

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

if (interface ~= nil) then
    if interface.name then                     
       content = content .. [[ 
                    <h3>Managing VLAN Profile "]]..interface.name..[["</h3>
    ]]
    edit_control = "readonly"
    option_control = "disabled"
    else 
       content = content .. [[
                    <h3>Adding new VLAN Profile</h3>
    ]] 
    interface.name = ""
    edit_control = ""
    option_control = ""
    end
       content = content .. [[
                    <div class="formLayoutfull">
                        <form action="network_vlan.lua" method="post" onsubmit="return ValidateForm(this);">
                            
]]
    local dhcp_checked = ""
    local enable_checked = ""
    local read_only = inputControl
    if interface.enabled == "enabled" then enable_checked = "checked" end
        content = content .. [[
                            <label for="enable">Enable this profile</label>
                            <input type="checkbox" value="enabled" name="profile" id="enable" ]]..enable_checked..[[ ]]..buttonControl..[[/><br>
                            <ul>
                                <li><label style="display: inline-block; width: 120px;">VLAN Label:</label> <input type="text" name="name" placeholder="Interface name" value="]]..interface.name..[["]]..edit_control..[[/></li>
                                <li><label style="display: inline-block; width: 120px;">Parent Profile:</label> <select name="parent"]]..edit_control..[[/>
                              ]]
                                                                                                               for i,parent in ipairs(parents) do
                                                                                                                    if interface.parent and interface.parent == parent then
         content = content .. [[                                                                                                                   
                                                                                                                     <option selected >]]..parent..[[</option>
                              ]]                                                                                        
                                                                                                                    
                                                                                                                    else
         content = content .. [[                                                                                                                   
                                                                                                                     <option ]]..option_control..[[ >]]..parent..[[</option>
                              ]]
                                                                                                                    end                                                                                         
                                                                                                               end                                                         
         content = content .. [[                                                                                                                   
                                                                                                                </select     
                                </li>
                                <li><label style="display: inline-block; width: 120px;">IP Address:</label> <input type="text" placeholder="IP Address" name="address" value="]]..interface.address..[["]]..read_only..[[/></li>
                            </ul>
]]
    content = content .. [[
                            <hr>
]]                            
    if (saved == 1) then
        content = content .. [[
                            <br><b><img src="images/ok.png"/> Changes saved, but may take a few seconds to take effect.</b><br><br>
]]
    end
    content = content .. [[
                            <input type="hidden" name="vlanid" value="]]..interface.vlanid..[["/>
                            <input type="button" name="backButton" value="Back to Interfaces" onclick="window.location.assign('network_interfaces.lua');"/>
                            <input type="Submit" name="submitButton" value="Save and Apply"]]..buttonControl..[[/>
                            <input type="Submit" name="deleteButton" value="Delete"]]..buttonControl..[[/>
                        </form>
                    </div>
                    <h3>Interface configuration</h3>
                    <pre class="formLayoutfull">
                    <!-- ifconfig start -->
]] 
.. ifconfigResult .. 
[[                  
                    <!-- ifconfig end -->
                    </pre>
]]
else
    content = content .. [[
                    <div id="info">
                        <center>
                            <h2><img src="images/warning.png"> No interfaces found</h2>
                            Either the interfaces file "]]..network_conf.interface_file..[[" is missing or unreadable,<br>
                            or none of the interfaces have been marked as being configurable.<br><br>
                            <a href="network_status.lua">View network status</a> for more information.
                        </center>
                    </div>]]
end

print(header..content..footer)
