require("luamods/command")
require("luamods/layout")
require("luamods/cgi")
require("config/software_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()

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

--Load the configuration and parse it into conf variable
conf = {}
confText=""
f = io.open(software_conf.opkg_conf_path,"r")
curr_section=nil
for line in f:lines() do
    confText = confText..line.."\n"
  --First find a section
  if not line:match("^#") and line:match("%[.+%]") then
     section = line:match("%[(.+)%]")
     curr_section={}
     table.insert(conf,curr_section)
     curr_section['text']=""
     curr_section['data']={}
     curr_section['name']=section
  else
    if curr_section then
      curr_section['text'] = curr_section['text']..line.."\n"
    end
  end
  if curr_section then
    if not line:match("^#") then
        k,v = line:match("(%S+)%s*=%s*(%S+)")
        if k then
           curr_section['data'][k]=v
           if k:match("[Include|Server|File]") then
              curr_section['mode']=k
              curr_section['url']=v
           end
        end
    end
  end
end

f:close()


if (cgi.post.submitButton == "Save and Update") and (userLevel ~= 1) then

local conf_prefix = [[

#
# /etc/pacman.conf
#
# See the pacman.conf(5) manpage for option and repository directives


]]

local mirror_prefix = [[
#
# List of Guinnux mirrors
# 

]]
local oldConf = conf
local newConf = ""
conf ={}
for idx,section in ipairs(oldConf) do
  if section.name == "options" then
    newConf = newConf.."[options]\n"..section.text
    table.insert(conf,options)
  end
end

    num = 0 
    for count = 1,10 do
        if (cgi.post["src"..count] ~= nil) then
            src = cgi.post["src"..count]
            mode = cgi.post["mode"..count] 
            path = cgi.post["path"..count] or ""
            logmsg("Adding:"..src..","..mode..","..path)
            if mode == "Include" then path = software_conf.opkg_mirror_list end
            if (src ~= "") then
                num = num + 1
                newConf = newConf .. "\n["..src.."]\n"..mode.." = "..path.."\n\n"
                sect = {};
                sect['name'] = src;
                sect['mode'] = mode;
                sect['url'] = path;
                table.insert(conf,sect);
            end
        end
    end
    command.writefile(software_conf.opkg_conf_path, newConf)
    confText = newConf
    newConf = mirror_prefix
    for count = 1,10 do
        if (cgi.post["arch"..count] ~= nil) then
            arch = cgi.post["arch"..count]
            if (arch ~= "") then
                num = num + 1
                newConf = newConf .. "Server = "..arch.."\n"
            end
        end
    end
    command.writefile(software_conf.opkg_mirror_list, newConf)
    

    if (num > 0) then
        saved = 1
        updateResults = command.ex(software_conf.opkg_update) or ""
    end
    
    
end

mirrorlist = command.ex("cat "..software_conf.opkg_mirror_list) or ""

-- This works but I don't know why. Haha oh boy

sources = {}
archs = {}
repos = {}
mirrors = {}






for mirror in string.gmatch(mirrorlist,"[^# ]+Server%s*=%s*(.-)%s*\n") do
    table.insert(mirrors,mirror)
end


content = [[
                    <div id="info">
                        <div style="background:url(images/software.png); background-size:32px; background-repeat:no-repeat; background-position: 20px center;">
                            <center><h1>Software - Repository Sources</h1></center>
                        </div>
                    </div>
]]



if (conf == "") then
    -- Bail on error
    content = content .. [[
                    <div id="info">
                        <center>
                            <h2><img src="images/warning.png"/> Cannot read config file</h2>
                            The package manager configuration file "]]..software_conf.opkg_conf_path..[[" is missing or unreadable.
                        </center>
                    </div>
]]
    print(header..content..footer)
    return     
else
    
    if (userLevel == 1) then
        content = content .. [[
                    <center><b>Note:</B> Editing this section requires administrator privileges.</center><br>
]]                    
    end    
    
    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 all_selects = field_area.getElementsByTagName("select"); //Get all the input fields in the given area.
                            var loop;
                            
                            if (field == "repo")
                            {
                              var idx;
                              for (loop = 0; loop < all_inputs.length; loop+=2)
                              {
                                  idx = loop/2;
                                  all_inputs[loop].name = "src"+(idx+1);
                                  all_inputs[(loop+1)].name = "path"+(idx+1);
                              }
                              for (loop = 0; loop < all_selects.length; loop+=1)
                              {
                                  all_selects[loop].name = "mode"+(loop+1);
                              }

                            }
                            else if (field == "arch")
                            {
                              for (loop = 0; loop < all_inputs.length; loop+=1)
                              {
                                      all_inputs[loop].name = "arch"+(loop+1);
                              }                            
                            }
                        }
                        
                        function changetextbox(idx)
                        {
                             var selects = document.getElementsByName("mode"+idx);
                             
                             if (document.getElementsByName("mode"+idx)[0].value == "Include") {
                                   document.getElementsByName("path"+idx)[0].disabled='true';
                             } else {
                                   document.getElementsByName("path"+idx)[0].disabled='';
                              }
                         }
                        
                        //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 (field == "repo")
                            {
                               count = count/2;
                            }
                            if(count+1 > limit && limit > 0) return;
                            
                            if(document.createElement)
                            { //W3C Dom method.
                                if (field == "repo")
                                {
                                    var li = document.createElement("li");
                                    
                                    var selectionmode = "<select  name=\"mode"+(count+1)+"\" id=\"myselect\" style=\"width:150px;\" onChange=\"changetextbox("+(count+1)+");\"><option value=\"File\">File</option> <option value=\"Server\">Server</option> <option value=\"Include\" selected>Include</option></select>"
                                    li.innerHTML = "<input name=\"src"+(count+1)+"\" style=\"width:150px;\" placeholder=\"Repository name\"/> " + selectionmode + "  <input type=\"text\" name=\"path"+(count+1)+"\" style=\"width:150px;\" placeholder=\"Path\" id=\"sdd\" disabled/><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 if (field == "arch")
                                {
                                    var li = document.createElement("li");
                                    li.innerHTML = "<input name=\"arch"+(count+1)+"\" style=\"width:400px;\" placeholder=\"Mirror URL\"/><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>
]]
if (saved == 1) and (updateResults ~= "") then
    content = content ..[[
                    <h3>Update Results</h3>
                    <pre CLASS="formLayoutfull">
]]..updateResults..[[
                    </pre>
]]
end

content = content .. [[
                    <h3>Add and remove the repository sources where packages may be downloaded from.</h3>
                    <div class="formLayoutfull">
                        <form action="software_sources.lua" method="post">
                            <h3>List of repositories</h3>
                            Enter the names of repositories<br>
                            The priority is provided by the order in which the repositories are listed
                            <ol id="repo_list">
]]
         local i = 1
        for name,section in ipairs(conf) do
           
            if section.name ~= "options" then
              logmsg("Mode = '"..section.mode.."'")
              local selectServer = ""
              if section.mode == "Server" then selectServer = "selected" logmsg("Select Server") end 
              local selectFile = ""
              if section.mode == "File" then selectFile = "selected" logmsg("Select File")end 
              local selectInclude = ""
              local pathValue=[[ value="]]..section.url..[["]]
              if section.mode == "Include" then 
                  selectInclude = "selected" 
                  pathValue=[[ disabled ]] 
                  logmsg("Select Include") 
               end 
              
              
              content = content .. [[
                                  <li><input type="text" name="src]]..i..[[" value="]]..section.name..[[" style="width: 150px;" placeholder="Repository name"]]..inputControl..[[/>
                                  <select  name="mode]]..i..[[" id="myselect" style=width:150px;" onChange="changetextbox(]]..i..[[);"><option value="File" ]]..selectFile..[[ >File</option> <option value="Server" ]]..selectServer..[[ >Server</option> <option value="Include" ]]..selectInclude..[[ >Include</option></select>
                                  <input type="text" name="path]]..i..[[" style="width:150px; placeholder="Path" id="sdd" ]]..pathValue..[[/>
                                  <a style="cursor:pointer;color:blue;" onclick="]]..scriptControl..[[removeField(this, 'repo');"><img src="images/trash.png" alt="Delete" title="Delete"/></a></li>
]]
               logmsg("Idx: "..i)
               i = i +1
               
            end
         end
    content = content .. [[
                            </ol>
                            <input type="button" value="Add Repository" onclick="addField('repo', 20);"]]..buttonControl..[[/>
                            <br><br><hr>
                            <h3>List of Repository Mirrors</h3>
                            Enter the mirror URLS here.<br>
                            <ol id="arch_list">
                            
                         ]]

    if (#(mirrors) > 0) then
        for i = 1, #(mirrors)  do
            if (i > 1) then
            content = content .. [[
                                <li><input type="text" name="arch]]..i..[[" value="]]..mirrors[i]..[[" style="width: 400px;" placeholder="Mirror URL"]]..inputControl..[[/><a style="cursor:pointer;color:blue;" onclick="]]..scriptControl..[[removeField(this, 'arch');"> <img src="images/trash.png" alt="Delete" title="Delete"/></a></li>
]]
            else
            content = content .. [[
                                <li><input type="text" name="arch]]..i..[[" value="]]..mirrors[i]..[[" style="width: 400px;" placeholder="Mirror URL"]]..inputControl..[[/></li>
]]
            end
        end
    else
            content = content .. [[
                                <li><input type="text" name="arch1" value="" style="width: 400px;" placeholder="Mirror URL"]]..inputControl..[[/></li>
]]                            
    end
    content = content .. [[
                            </ol>
                            <input type="button" value="Add Mirror" onclick="addField('arch', 20);"]]..buttonControl..[[/><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 Update"]]..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('opkg'));">View ]]..software_conf.opkg_conf_path..[[</a></a><br>
        
                    <div id="opkg" style="display: none;">        
                        <pre class="formLayoutfull">
                        <!-- opkg start -->
]]..confText..[[
                        <!-- opkg end -->
                        </pre>
                    </div>
]]  
end

print(header..content..footer)
