local command = require("luamods/command")
local layout = require("luamods/layout")
local cgi = require("luamods/cgi")
local canbus_conf = require("config/canbus_conf")
local lfs = require("lfs")

local interfaces = {}


function get_link_state(ifname)
  local result = command.ex("ip -det link show dev "..ifname.."  2>&1")
  local if_state = result:match(".+state%s(%u-)%s.+") or "DOWN"
  local bit_rate = result:match(".+bitrate%s(%u-)%s.+") or "-"
  return if_state
end

function get_link_stats(ifname)
   local result = command.ex("ifconfig "..ifname.."  2>&1")
   local rx_packets = result:match("RX packets%s+(%S+)")
   local tx_packets = result:match("TX packets%s+(%S+)")
   return rx_packets,tx_packets
end

function generate_config_files(interfaces)
   for _,bus in ipairs(interfaces) do
   local file_name = canbus_conf.profile_path.."/"..bus.name..".network"
   local cfg_string = [[
#This is generated by the webconfig

[Match]
Name=]]..bus.name..[[

]] 
   if bus.bit_rate ~= "-" then
cfg_string = cfg_string..[[


[CAN]
BitRate=]]..bus.bit_rate..[[   
   
]]         
   end
   command.writefile(file_name,cfg_string)      
   end
end

command.log("Looking in: "..canbus_conf.profile_path)
for file in lfs.dir(canbus_conf.profile_path) do
    local f = canbus_conf.profile_path..'/'..file
    local attr = lfs.attributes (f)
    if attr.mode ~= "directory" and file:match(".+%.network") then
      command.log("Profile: "..file)
      profile = {}
      profile.name = file:match('(.+)%.network')
      local cfg_file = io.open(f,"r")
      profile.bit_rate = "-"
      for cfg_line in cfg_file:lines() do
         if  cfg_line:match("BitRate") ~= nil then
            profile.bit_rate = cfg_line:match("BitRate%s*=%s*(%S+)")
            command.log("Found bit_rate: "..profile.bit_rate)
         end

      end
      profile.config = ""
      profile.link_state = get_link_state(profile.name)
      profile.rx_packets,profile.tx_packets = get_link_stats(profile.name)
      table.insert(interfaces,profile)
    end
end

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

   for _,interface in ipairs(interfaces) do
      interface.bit_rate = cgi.post[interface.name.."_bit_rate"] or "-"
   end
   generate_config_files(interfaces)
   command.ex(canbus_conf.restart)
   saved = true
else
   saved = false   
end


local datamodel = {}
datamodel.interfaces = interfaces
datamodel.saved = saved

layout.renderLayout("templates/canbus_interfaces.html",datamodel)