require("luamods/command")
require("luamods/cgi")
require("config/time_conf")
require("luamods/layout")

lfs = require("lfs")

userLevel = db.getPriv(layout.username) or 1

if (userLevel == 1) then
    buttonControl = " disabled"
    inputControl = " readonly"
else
    buttonControl = ""
    inputControl = ""
end

if (cgi.post.submitButton == "Save and Apply") and (userLevel ~= 1) then
    
    ntpServer = cgi.post.ntpServer
    newDate = cgi.post.dateInput
    newTime = cgi.post.timeInput
    newTimeZone = cgi.post.tzselect
    
    result = ""
    
    if (newDate ~= nil) and (newTime ~= nil) then
        
        if (ntpServer ~= nil) then
            result = result .. command.ex(time_conf.ntp_stop)
            value = "tinker panic 0\nlogfile "..time_conf.ntp_logfile_path.."\ndriftfile "..time_conf.ntp_driftfile_path.."\nserver "..ntpServer.."\n"
            scf = io.open (time_conf.ntp_conf_path,"w+")
            scf:write(value)
            scf:close()
            result = result .. command.ex(time_conf.ntp_start)
        end
        
        result = result .. command.ex([[date --set="]]..newDate..[[ ]]..newTime..[[" +"%Y-%M-%d %H:%m:%S"]])
        result = result .. command.ex(time_conf.hwclock_set)
        
        saved = 1
    end
    if newTimeZone ~= nil then
        result = result .. command.ex([[ln -sf ]]..time_conf.zoneinfo_path..[[/]]..newTimeZone..[[ ]]..time_conf.localtime_path)
        saved = 1
    end
end


local function msg(m)
  command.ex([[echo "]]..m..[[" >>  /var/log/lighttpd_cgi.log ]])
end   

--****** Get the time as a string ******--

sysTimeString = command.ex("date +\"%H:%M:%S\""):match("%s*(.-)\n")
sysDateString = command.ex("date +\"%Y-%m-%d\""):match("%s*(.-)\n")

ntpconf = command.ex("cat "..time_conf.ntp_conf_path)

ntpserver = string.match(ntpconf,"server ([^\n]+)") or ""

--****** Now get all the Time Zone bits and pieces ******--
local function zone_sort(a,b)
   if a.name < b.name then return true end
   return false     
end


local zoneinfo = {}
local current_timezone = command.ex("realpath --relative-to=/usr/share/zoneinfo/ /etc/localtime" )
local current_region,current_zone = current_timezone:match("(.+)/(.+)\n")

for file in lfs.dir(time_conf.zoneinfo_path) do
    local f = time_conf.zoneinfo_path..'/'..file
    local attr = lfs.attributes (f)
    if attr.mode == "directory" and file ~= '.' and file ~= ".." and file ~= "right" and file ~= "posix" then
        local region = {}
        for zone in lfs.dir(time_conf.zoneinfo_path..'/'..file) do
            local fz =time_conf.zoneinfo_path..'/'..file..'/'..zone
            local zattr = lfs.attributes (fz)
            if zattr.mode == "file" and zone ~= '.' and zone ~= ".." then
              table.insert(region,zone)
            end
        end
        region['name']=file
        table.insert(zoneinfo,region)
    end
end


header = layout.getHeader()
footer = layout.getFooter()
content = [[
                    <div id="info">
                        <div style="background:url(images/clock.png); background-size:32px; background-repeat:no-repeat; background-position: 20px center;">
                            <center><h1>Date and Time</h1></center>
                        </div>
                    </div>
]]

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


if (ntpconf == "") then
    -- Don't bail, just warn
    content = content .. [[
                    <div id="info">
                        <center>
                            <h2><img src="images/warning.png"/> Cannot read config file</h2>
                            The NTP daemon configuration file "]]..time_conf.time_conf.ntp_conf_path..[[" is missing or unreadable.<br>
                        </center>
                    </div>
]]
    --print(header..content..footer)
    --return
end
content = content..[[

                    <script>
                    
                        function validateForm(f)
                        {
                            if (f.getAttribute('submitted')) return false;
                            
                            var dI = document.getElementById("dateInput");
                            var tI = document.getElementById("timeInput");
                            
                            var warn = document.getElementById("invalidDate");
                            if (warn)
                            {
                                warn.parentNode.removeChild(warn);
                            }
                            warn = document.getElementById("invalidTime");
                            if (warn)
                            {
                                warn.parentNode.removeChild(warn);
                            }                                
                            
                            if (parseDate(dI.value) == null)
                            {
                                alert("Please enter a valid date in the format YYYY-MM-DD");
                                var warn = document.createElement("span");
                                warn.id = "invalidDate";
                                warn.innerHTML = " <img src='images/warning.png' alt='Invalid Format' title='Invalid Format'/>";
                                dI.parentNode.appendChild(warn);
                                return false;
                            }
                            
                            if (!parseTime(tI.value))
                            {
                                alert("Please enter a valid time in the format HH:mm:ss");
                                var warn = document.createElement("span");
                                warn.id = "invalidTime";
                                warn.innerHTML = " <img src='images/warning.png' alt='Invalid Format' title='Invalid Format'/>";
                                tI.parentNode.appendChild(warn);
                                return false;
                            }
                            
                            f.setAttribute('submitted','true');
                            return true;
                        }                    
                    
                        function getDefaultNTP()
                        {
                            document.getElementById("ntpServer").value = "]]..time_conf.ntp_default_server..[[";
                        }
                    
                        function parseDate(str)
                        {
                            var t = str.match(/^(\d{4})\-(\d{2})\-(\d{2})$/);
                            if (t !== null)
                            {
                                var d=+t[3], m=+t[2], y=+t[1];
                                var date = new Date(y,m-1,d);
                                if (date.getFullYear()===y && date.getMonth()===m-1)
                                {
                                    return date;   
                                }
                            }
                            return null;
                        }
                        
                        function parseTime(str)
                        {
                            var t = str.match(/^(\d{2})\:(\d{2})\:(\d{2})$/);
                            if (t !== null)
                            {
                                if ((t[1] < 24) && (t[2] < 60) && (t[3] < 60))
                                {
                                    return true;
                                }
                            }
                            return false;
                        }
                        
                        function setToPcDateTime()
                        {
                            var MyDate = new Date();
                            var MyDateString;
                            var MyTimeString;

                            MyDateString = MyDate.getFullYear() + "-" + 
                                ('0' + (MyDate.getMonth()+1)).slice(-2) + "-" + 
                                ('0' + (MyDate.getDate())).slice(-2);
                                
                            MyTimeString = ('0' + MyDate.getHours()).slice(-2) + ":" + 
                                ('0' + MyDate.getMinutes()).slice(-2) + ":" + 
                                ('0' + MyDate.getSeconds()).slice(-2);
                                
                                
                            document.getElementById("dateInput").value = MyDateString;
                            document.getElementById("timeInput").value = MyTimeString;
                        }
                        
                    </script>
                    
                    <div class="formLayoutfull">
                        <h3>Current system date and time:</h3>
                        <pre>
Software clock: ]] .. command.ex(time_conf.swclock_read) .. [[
Hardware clock: ]] .. command.ex(time_conf.hwclock_read) .. [[
                        </pre>
                        <hr>
                        <form action="datetime.lua" method="post" onsubmit="return validateForm(this);">
]]
    -- Disable this part of the form of ntp.conf is missing or blank
if (ntpconf == "") then
    content = content .. [[
                            <h3>Network Time Protocol (NTP) settings: <img src="images/warning.png" title="Cannot read NTP config" alt="Cannot read NTP config"/></h3>
                            <label style="display: inline-block; width: 100px;">Time Server: </label>
                            <input type="text" name="ntpServer" id="ntpServer" value="" readonly/>
                            <input type="button" name="ntpButton" value="Get default value" disabled/><br><br>
]]                            
else
    content = content .. [[
                            <h3>Network Time Protocol (NTP) settings: </h3>
                            <label style="display: inline-block; width: 100px;">Time Server: </label>
                            <input type="text" name="ntpServer" id="ntpServer" value="]]..ntpserver..[["]]..inputControl..[[/>
                            <input type="button" name="ntpButton" value="Get default value" onclick="getDefaultNTP();"]]..buttonControl..[[/><br><br>
]]
end


content = content .. [[
                    <hr>
                    <h3>Timezone settings: </h3>
                    <label style="display: inline-block; width: 100px;">Timezone: </label> 
                    <select name="tzselect" style="width: 180px">]]
                        table.sort(zoneinfo,zone_sort)
                        for k,v in pairs(zoneinfo) do
content = content .. [[<optgroup label="]]..v.name..[[">]]                        
                        table.sort(v)
                           for zk,zv in ipairs(v) do
                              if current_region == v.name and current_zone == zv then
content = content .. [[<option value="]]..v.name.."/"..zv..[[" selected>]]..zv..[[</option>]]
                              else
content = content .. [[<option value="]]..v.name.."/"..zv..[[">]]..zv..[[</option>]]
                              end 
                           end
content = content .. [[</optgroup>]]                           
                        end
content = content .. [[</select>
                    
]]




content = content .. [[    
                            <hr>
                            <h3>Manual time and date settings: </h3>
                            <ul>
                                <li>
                                    <label style="display: inline-block; width: 50px;">Date: </label>
                                    <input type="text" name="dateInput" id="dateInput" value="]]..sysDateString..[["]]..inputControl..[[/> (YYYY-MM-DD)
                                </li>
                                <li>
                                    <label style="display: inline-block; width: 50px;">Time: </label>
                                    <input type="text" name="timeInput" id="timeInput" value="]]..sysTimeString..[["]]..inputControl..[[/> (HH:mm:ss)
                                </li>
                            </ul>
                            <input type="button" value="Get date and time from PC" onclick="setToPcDateTime();"]]..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="Reset" name="resetButton" value="Undo"]]..buttonControl..[[/>
                            <input type="Submit" name="submitButton" value="Save and Apply"]]..buttonControl..[[/>
                        </form>
                    </div>
]]

print(header..content..footer)
