require("luamods/command")
require("luamods/layout")
require("luamods/cgi")
require("config/network_conf")
json = require("json")
lfs = require("lfs")

wanbackup_conf="/etc/wanbackup.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()

if (cgi.post.submitButton == "Save and Apply") and (userLevel ~= 1) then
    saved = 1
end

currCfg = command.ex("cat "..wanbackup_conf)

if (currCfg ~= "none" and currCfg ~= "") then
    cfg = json.decode(currCfg)
    local out,status =  command.ex("systemctl is-enabled wanbackup")
    if status then
      cfg.enabled = true
    else
      cfg.enabled = false
    end
    local jsonCfg = ""   
    if (saved == 1) then
        local newCfg={}
        newCfg.backup_profile = cgi.post.backup or ""
        newCfg.wan_profile = cgi.post.wan or ""
        newCfg.link_test_ip = cgi.post.testip or ""
        if cgi.post.profile == "enabled" then
          newCfg.enabled = true
        else
          newCfg.enabled = false 
        end
        
        jsonCfg = json.encode(newCfg)
        jsonCfg = jsonCfg:gsub('[{,]','%1\n')
        jsonCfg = jsonCfg:gsub('}','\n%1')
        
        command.writefile(wanbackup_conf, jsonCfg)

        if newCfg.enabled ~= cfg.enabled then
           if newCfg.enabled == true then
              command.ex("systemctl enable wanbackup")
           else
              command.ex("systemctl disable wanbackup")
           end
        end

        cfg = newCfg  
        if cfg.enabled == true then
           command.ex("systemctl restart wanbackup")
        else
           command.ex("systemctl stop wanbackup")
        end
    end
    ifconfigResult = jsonCfg
    
else
    content = [[
                    <div id="info"><center><H1>WAN Backup / Failover Configuration</H1></center></div>
                    <div id="info">
                        <center>
                            <h2><img src="images/warning.png"/> Cannot load the configuration details</h2>
                            Have a look at the configuration file at "]]..wanbackup_conf..[["<br>
                            The wanbackup application will recreate a valid default configuration if this file is missing<br><br>
                            <a href="index.lua">Back to Home Page</a>
                        </center>
                    </div>
]]
    html = header..content..footer
    print(html)
    return        
end    

profiles={}
for file in lfs.dir(network_conf.netctl_profile_path) do
    local f = network_conf.netctl_profile_path..'/'..file
    local attr = lfs.attributes (f)
    if attr.mode == "file" and file ~= '.' and file ~= ".." then
       local file_cfg = command.ex("cat "..network_conf.netctl_profile_path..'/'..file)
       local desc = file_cfg:match("Description='(.-)'\n") or ""
       profiles[file] = desc
    end
end

content = ""

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

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

if (cfg ~= nil) then
    content = content .. [[
                    <div class="formLayoutfull">
                        <form action="wanbackup_web.lua" method="post">
                            
]]
    local enable_checked = ""
    local read_only = inputControl
    if cfg.enabled == true then enable_checked = "checked" end
    content = content .. [[
                            <label for="enable">Enable WAN backup service</label>
                            <input type="checkbox" value="enabled" name="profile" id="enable" ]]..enable_checked..[[ ]]..buttonControl..[[/><br>
                            <ul>
                                <li>
                                      <label style="display: inline-block; width: 120px;">WAN Profile:</label> 
                                      <select name="wan" ]]..read_only..[[>
]] 
                                           for k,v in pairs(profiles) do
                                             if k == cfg.wan_profile then
   content = content..[[                     <option value="]]..k..[[" selected>]]..k..[[ - ]]..v..[[</option>]]
                                             else
   content = content..[[                     <option value="]]..k..[[">]]..k..[[ - ]]..v..[[</option>]]
                                             end                                           
                                           end                                                                         
   content = content..[[              </select>
                                </li>
                                <li>
                                      <label style="display: inline-block; width: 120px;">Backup Profile:</label>
                                      <select name="backup" ]]..read_only..[[>
]] 
                                           for k,v in pairs(profiles) do
                                             if k == cfg.backup_profile then
   content = content..[[                     <option value="]]..k..[[" selected>]]..k..[[ - ]]..v..[[</option>]]
                                             else
   content = content..[[                     <option value="]]..k..[[">]]..k..[[ - ]]..v..[[</option>]]
                                             end                                           
                                           end                                                                         
   content = content..[[              </select>
                               </li>
                                <li><label style="display: inline-block; width: 120px;">Test IP:</label> <input type="text" name="testip" value="]]..cfg.link_test_ip..[["]]..read_only..[[/></li>
                            </ul>
                            <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="Submit" name="submitButton" value="Save and Apply"]]..buttonControl..[[/>
                        </form>
                    </div>]]
else
    content = content .. [[
                    <div id="info">
                        <center>
                            <h2><img src="images/warning.png"/> Cannot load the configuration details</h2>
                            Have a look at the configuration file at "]]..wanbackup_conf..[["<br>
                            The wanbackup application will recreate a valid default configuration if this file is missing<br><br>
                            Here is what I know: ']]..currCfg..[['
                            <a href="index.lua">Back to Home Page</a>
                        </center>
                    </div>]]
end

print(header..content..footer)
