#!/usr/bin/luaweb
json = require("json")
omg = require("omg")

local osType = omg.getOsType()
local osVersion = omg.getOsVersion()

local newCentos = false

if (osType == "centos" or osType=="red") and (osVersion=="7" or osVersion=="8") then
   newCentos = true
end

helpString=omg.getHelpString(arg[0],"init or set network configuration\n")
if newCentos then
   helpString=helpString .. "\t--restore\trestore config saved with omgbackupnetwork\n"
   helpString=helpString .. "\t--merge\tmerge eeprom to network manager\n"
end

function readAll(file)
   local f = io.open(file, "rb")
   local content = f:read("*all")
   f:close()
   return content
end

function execute(command)
   local handle = io.popen(command)
   local result = handle:read("*a")
   handle:close()
  
   if result ~= nil then
      result = string.gsub(result,"\n","")
   end

   return result
end

function omg.getHelpString(name,desc)
   return helpString
end

myOptions=omg.splitCommandlineString(arg)

local archiveToRestore=""
print(archiveToRestore)
if newCentos and myOptions.restore == true then
   archiveToRestore="/data/networksettingsbackup.cfg"
elseif myOptions.restore ~= nil then
   archiveToRestore=myOptions.restore
end
if string.len(archiveToRestore) > 0 then
   execute('omgrestorenetwork ' .. archiveToRestore)
end

if myOptions.help == nil and string.len(archiveToRestore) == 0 then
   if newCentos and myOptions.merge==nil then
      f = io.open("/etc/sysconfig/network-scripts/ifcfg-eth0", "r")
      if f then
         f:close()
         return
      end
   end

   if osType == "ubuntu" then
      omg.execute('/etc/init.d/omg.netconfig')
   elseif (osType == "centos" or osType=="red") then
      local nmUsed="yes"
      if osVersion=="6" then
         nmUsed="no"
      end
      --test
      
      local eeprom = omg.cmd2TreeTable("omgenvironment --dump", ".", "=")
      --print(omg.dumpTableToDelimiterList(eeprom,".","="))

      local networking={}
      networking["global"]=omg.cmd2TreeTable("cat /etc/sysconfig/network", ".", "=")

      networking.bond0 = omg.cmd2TreeTable("cat /etc/sysconfig/network-scripts/ifcfg-bond0", ".", "=")
      networking.eth0 = omg.cmd2TreeTable("cat /etc/sysconfig/network-scripts/ifcfg-eth0", ".", "=")
      networking.eth1 = omg.cmd2TreeTable("cat /etc/sysconfig/network-scripst/ifcfg-eth1", ".", "=")
      networking.eth2 = omg.cmd2TreeTable("cat /etc/sysconfig/network-scripst/ifcfg-eth2", ".", "=")
      networking.eth3 = omg.cmd2TreeTable("cat /etc/sysconfig/network-scripst/ifcfg-eth3", ".", "=")
      networking.eth4 = omg.cmd2TreeTable("cat /etc/sysconfig/network-scripst/ifcfg-eth4", ".", "=")
      networking.eth5 = omg.cmd2TreeTable("cat /etc/sysconfig/network-scripst/ifcfg-eth5", ".", "=")
      networking.eth6 = omg.cmd2TreeTable("cat /etc/sysconfig/network-scripst/ifcfg-eth6", ".", "=")
      networking.eth7 = omg.cmd2TreeTable("cat /etc/sysconfig/network-scripst/ifcfg-eth7", ".", "=")

      ip=omg.cmd2TreeTable("omgnetworkinfo", "\.", "=")
      --print(omg.dumpTableToDelimiterList(ip,".","="))
      
      local iterator={}

      if ip.eth0~=nil and string.len(ip.eth0.available) > 0 then
         iterator[1]={}
         iterator[1].port="eth0"
         iterator[1].prefix="IP_"
         iterator[1].zone="internal"
      end

      if ip.eth1~=nil and string.len(ip.eth1.available) > 0 then
         iterator[2]={}
         iterator[2].port="eth1"
         iterator[2].prefix="IP2_"
         iterator[2].zone="public"
      end   

      if ip.eth2~=nil and string.len(ip.eth2.available) > 0 then
         iterator[3]={}
         iterator[3].port="eth2"
         iterator[3].prefix="IP3_"
         iterator[3].zone="public"
      end   

      if ip.eth3~=nil and string.len(ip.eth3.available) > 0 then
         iterator[4]={}
         iterator[4].port="eth3"
         iterator[4].prefix="IP4_"
         iterator[4].zone="public"
      end   

      if ip.eth4~=nil and string.len(ip.eth4.available) > 0 then
         iterator[5]={}
         iterator[5].port="eth4"
         iterator[5].prefix="IP5_"
         iterator[5].zone="public"
      end   

      if ip.eth5~=nil and string.len(ip.eth5.available) > 0 then
         iterator[6]={}
         iterator[6].port="eth5"
         iterator[6].prefix="IP6_"
         iterator[6].zone="public"
      end   

      if ip.eth6~=nil and string.len(ip.eth6.available) > 0 then
         iterator[7]={}
         iterator[7].port="eth6"
         iterator[7].prefix="IP7_"
         iterator[7].zone="public"
      end   

      if ip.eth7~=nil and string.len(ip.eth7.available) > 0 then
         iterator[8]={}
         iterator[8].port="eth7"
         iterator[8].prefix="IP8_"
         iterator[8].zone="public"
      end   

      if (ip.bond0~=nil and string.len(ip.bond0.available) > 0) or (eeprom["IPB_DHCPMODE"]~=nil) then
         iterator[9]={}
         iterator[9].port="bond0"
         iterator[9].prefix="IPB_"
         iterator[9].zone="public"
      end
   
      
      for _,i in pairs(iterator) do
         local bootproto
         local autoconf
         local init
         local var
         local dnsCount=1

         if (newCentos and myOptions.merge==nil) then
            networking[i.port]=nil
            networking[i.port]={}
            networking[i.port]["DEVICE"]=i.port
            networking[i.port]["TYPE"]="Ethernet"
            networking[i.port]["BOOTPROTO"]="dhcp"      
            networking[i.port]["DEFROUTE"]="yes"      
            networking[i.port]["NM_CONTROLLED"]="yes"      
            networking[i.port]["USERCTL"]="no"
            networking[i.port]["ONBOOT"]="yes"
            networking[i.port]["PROXY_METHOD"]="none"
            networking[i.port]["BROWSER_ONLY"]="no"
            networking[i.port]["IPV4_FAILURE_FATAL"]="no"
            networking[i.port]["IPV6_DISABLED"]="yes"
            networking[i.port]["IPV6INIT"]="no"
            networking[i.port]["NAME"]=i.port
            networking[i.port]["IPV6_AUTOCONF"]="no"
            networking[i.port]["IPV6_DEFROUTE"]="yes"
            networking[i.port]["IPV6_PEERDNS"]="no"
            networking[i.port]["IPV6_PEERROUTES"]="no"
            networking[i.port]["IPV6_FAILURE_FATAL"]="no"
            networking[i.port]["IPV6_ADDR_GEN_MODE"]="stable-privacy"
            networking[i.port]["ZONE"]=i.zone
         else
            var = i.prefix .. "DHCPMODE"
            if eeprom[var] == "BOND" then
               networking[i.port]=nil
               networking[i.port]={}
               networking[i.port]["DEVICE"]=i.port
               networking[i.port]["USERCTL"]="no"
               networking[i.port]["ONBOOT"]="yes"
               networking[i.port]["MASTER"]="bond0"
               networking[i.port]["SLAVE"]="yes"
               networking[i.port]["BOOTPROTO"]="none"
            elseif eeprom[var] == nil and i.port=="bond0" then
               networking[i.port]=nil
               networking[i.port]={}
            else
               networking[i.port]["MASTER"]=nil
               networking[i.port]["SLAVE"]=nil
               if eeprom[var] == "STATIC" then
                  bootproto="none"
                  networking[i.port]["BOOTPROTO"]=bootproto
                  networking[i.port]["ONBOOT"]="yes"
               elseif eeprom[var] == "CLIENT" then
                  bootproto="dhcp"
                  networking[i.port]["BOOTPROTO"]=bootproto
                  networking[i.port]["ONBOOT"]="yes"
            -- Clear global static gateway
                  if i.port=="eth0" then
                     networking["global"]["GATEWAY"]=nil
                  end

               elseif eeprom[var] == "OFF" then
                  bootproto="dhcp"
                  networking[i.port]["BOOTPROTO"]=bootproto
                  networking[i.port]["ONBOOT"]="no"
               else
                  bootproto="dhcp"
                  networking[i.port]["BOOTPROTO"]=bootproto
                  networking[i.port]["ONBOOT"]="yes"
               end

               networking[i.port]["PERSISTENT_DHCLIENT"]="no"
               networking[i.port]["NM_CONTROLLED"]=nmUsed
               networking[i.port]["DEVICE"]=i.port
               networking[i.port]["TYPE"]="ETHERNET"
               networking[i.port]["USERCTL"]="no"
               if i.port=="eth0" then
                  networking[i.port]["PEERDNS"]="yes"
                  networking[i.port]["DEFROUTE"]="yes"
               else
                  networking[i.port]["PEERDNS"]="no"
                  networking[i.port]["DEFROUTE"]="no"
               end
               --commented for better portability of sd-cards
               --networking[i.port]["HWADDR"]=ip[i.port]["link"]["macAddress"]
               if networking[i.port]["HWADDR"] ~=nil then
                  networking[i.port]["HWADDR"]=nil
               end

               if bootproto == "dhcp" then
                  var = i.prefix .. "ADDRESS"
                  networking[i.port]["IPADDR"]=nil
                  networking[i.port]["GATEWAY"]=nil
                  networking[i.port]["NETMASK"]=eeprom[var]
                  networking[i.port]["DOMAIN"]=nil
                  networking[i.port]["DNS1"]=nil
                  networking[i.port]["DNS2"]=nil
                  networking[i.port]["DNS3"]=nil
                  networking[i.port]["DNS4"]=nil
               end
               
               if bootproto == "none" then
                  networking[i.port]["DNS1"]=nil
                  networking[i.port]["DNS2"]=nil
                  networking[i.port]["DNS3"]=nil
                  networking[i.port]["DNS4"]=nil

                  var = i.prefix .. "ADDRESS"
                  if eeprom[var] == nil then
                     networking[i.port]["IPADDR"]=nil
                  else
                     networking[i.port]["IPADDR"]=eeprom[var]
                  end

                  var = i.prefix .. "MASK"
                  if eeprom[var] == nil then
                     networking[i.port]["NETMASK"]=nil
                  else
                     networking[i.port]["NETMASK"]=eeprom[var]
                  end

                  var = i.prefix .. "DNS1"
                  if eeprom[var] ~= nil then
                     networking[i.port]["DNS"..dnsCount]=eeprom[var]
                     dnsCount=dnsCount+1
                  end

                  var = i.prefix .. "DNS2"
                  if eeprom[var] ~= nil then
                     networking[i.port]["DNS"..dnsCount]=eeprom[var]
                     dnsCount=dnsCount+1
                  end

                  var = i.prefix .. "DOMAIN"
                  if eeprom[var] == nil then
                     networking[i.port]["DOMAIN"]=nil
                  else
                     networking[i.port]["DOMAIN"]=eeprom[var]
                  end

                  var = i.prefix .. "GW"
                  if eeprom[var] ~= nil then
                     networking["global"]["GATEWAY"]=eeprom[var]
                  end
                  if networking[i.port]["GATEWAY"]~=nil then
                     networking[i.port]["GATEWAY"]=nil
                  end
               end

               var = i.prefix .. "DHCPMODE_6"
               if eeprom[var] == "STATIC" then
                  autoconf="no"
                  init="yes"
                  networking[i.port]["IPV6_FAILURE_FATAL"]="yes"
               elseif eeprom[var] == "AUTO" then
                  autoconf="yes"
                  init="yes"
                  networking[i.port]["IPV6_FAILURE_FATAL"]="yes"
               elseif eeprom[var] == "OFF" then
                  autoconf="no"
                  init="no"
                  networking[i.port]["IPV6_FAILURE_FATAL"]="no"
               end

               if (newCentos==false) then
                  if init == "yes" then
                     os.execute('if grep -q "^net.ipv6.conf.' .. i.port .. '.disable_ipv6=" /etc/sysctl.conf;then sed -i -e "/^net.ipv6.conf.' .. i.port .. '.disable_ipv6=/cnet.ipv6.conf.' .. i.port .. '.disable_ipv6=0" /etc/sysctl.conf;else echo "\n# Controls IPv6 is available for ' .. i.port .. ' or not\nnet.ipv6.conf.' .. i.port .. '.disable_ipv6=0" >> /etc/sysctl.conf;fi')
                  else
                     os.execute('if grep -q "^net.ipv6.conf.' .. i.port .. '.disable_ipv6=" /etc/sysctl.conf;then sed -i -e "/^net.ipv6.conf.' .. i.port .. '.disable_ipv6=/cnet.ipv6.conf.' .. i.port .. '.disable_ipv6=1" /etc/sysctl.conf;else echo "\n# Controls IPv6 is available for ' .. i.port .. ' or not\nnet.ipv6.conf.' .. i.port .. '.disable_ipv6=1" >> /etc/sysctl.conf;fi')
                  end
               end

               networking[i.port]["IPV6INIT"]=init
               networking[i.port]["IPV6_AUTOCONF"]=autoconf

               if init ~= "yes" or autoconf == "yes" then
                  var = i.prefix .. "ADDRESS_6"
                  local var2 = i.prefix .. "MASK_6"
                  networking[i.port]["IPV6ADDR"]=nil
                  networking[i.port]["IPV6_DEFAULTGW"]=nil
                  networking[i.port]["DNS3"]=nil
                  networking[i.port]["DNS4"]=nil
               end

               if init == "yes" and autoconf == "no" then
                  var = i.prefix .. "ADDRESS_6"
                  local var2 = i.prefix .. "MASK_6"
                  if eeprom[var] == nil then
                     networking[i.port]["IPV6ADDR"]=nil
                  else
                     networking[i.port]["IPV6ADDR"]=eeprom[var].."/"..(eeprom[var2] or "64")
                  end

                  var = i.prefix .. "DNS1_6"
                  if eeprom[var] ~= nil then
                     networking[i.port]["DNS"..dnsCount]=eeprom[var]
                     dnsCount=dnsCount+1
                  end

                  var = i.prefix .. "DNS2_6"
                  if eeprom[var] ~= nil then
                     networking[i.port]["DNS"..dnsCount]=eeprom[var]
                     dnsCount=dnsCount+1
                  end

                  var = i.prefix .. "DOMAIN_6"
                  if eeprom[var] == nil then
                     --do nothing
                     networking[i.port]["DOMAIN"]=networking[i.port]["DOMAIN"]
                  elseif eeprom[var] == networking[i.port]["DOMAIN"] then
                     --do nothing
                     networking[i.port]["DOMAIN"]=networking[i.port]["DOMAIN"]
                  else
                     if networking[i.port]["DOMAIN"] ~= nil then
                        networking[i.port]["DOMAIN"]='"' .. (networking[i.port]["DOMAIN"] or "") .. " " .. eeprom[var] .. '"'
                     else
                        networking[i.port]["DOMAIN"]=eeprom[var]
                     end
                  end

                  var = i.prefix .. "GW_6"
                  if eeprom[var] == nil then
                     networking["global"]["IPV6_DEFAULTGW"]=nil
                  else
                     networking["global"]["IPV6_DEFAULTGW"]=eeprom[var]
                  end
                  if networking[i.port]["IPV6_DEFAULTGW"]~=nil then
                     networking[i.port]["IPV6_DEFAULTGW"]=nil
                  end

                  --[[
                     var = i.prefix .. "GW_6"
                     if eeprom[var] == nil then
                     networking[i.port]["IPV6_DEFAULTGW"]=nil
                     else
                     networking[i.port]["IPV6_DEFAULTGW"]=eeprom[var]
                     end
                  ]]
               end
            end
         end
      end

      if os.execute("grep -q '^#LOCKED$' /etc/resolv.conf.save 2>/dev/null") ~= 0 then
         os.execute("echo 'options attempts:1' >/etc/resolv.conf.save")
         os.execute("echo 'options timeout:3' >>/etc/resolv.conf.save")
      end

      if os.execute("grep -q '^#LOCKED$' /etc/resolv.conf 2>/dev/null") ~= 0 then
         os.execute("echo '' >/etc/resolv.conf")
      end

      if networking.global~=nil then
         local f
         f = io.open("/etc/sysconfig/network", "w")
         if f then
            local s = omg.dumpTableToDelimiterList(networking.global,".","=")
            f:write(s)
            f:close()
         end
      end

      if networking.eth0~=nil and networking.eth0["BOOTPROTO"] ~= nil then
         local f
         f = io.open("/etc/sysconfig/network-scripts/ifcfg-eth0", "w")
         if f then
            local s = omg.dumpTableToDelimiterList(networking.eth0,".","=")
            f:write(s)
            f:close()
         end
         if osVersion=="6" then
            os.execute("ln -f /etc/sysconfig/network-scripts/ifcfg-eth0 /etc/sysconfig/networking/devices")
         end
      end

      if networking.eth1~=nil and networking.eth1["BOOTPROTO"] ~= nil then
         f = io.open("/etc/sysconfig/network-scripts/ifcfg-eth1", "w")
         if f then
            local s = omg.dumpTableToDelimiterList(networking.eth1,".","=")
            f:write(s)
            f:close()
         end
         if osVersion=="6" then
            os.execute("ln -f /etc/sysconfig/network-scripts/ifcfg-eth1 /etc/sysconfig/networking/devices")
         end
      end

      if networking.eth2~=nil and networking.eth2["BOOTPROTO"] ~= nil then
         f = io.open("/etc/sysconfig/network-scripts/ifcfg-eth2", "w")
         if f then
            local s = omg.dumpTableToDelimiterList(networking.eth2,".","=")
            f:write(s)
            f:close()
         end
         if osVersion=="6" then
            os.execute("ln -f /etc/sysconfig/network-scripts/ifcfg-eth2 /etc/sysconfig/networking/devices")
         end
      end

      if networking.eth3~=nil and networking.eth3["BOOTPROTO"] ~= nil then
         f = io.open("/etc/sysconfig/network-scripts/ifcfg-eth3", "w")
         if f then
            local s = omg.dumpTableToDelimiterList(networking.eth3,".","=")
            f:write(s)
            f:close()
         end
         if osVersion=="6" then
            os.execute("ln -f /etc/sysconfig/network-scripts/ifcfg-eth3 /etc/sysconfig/networking/devices")
         end   
      end

      if networking.bond0~=nil and networking.bond0["BOOTPROTO"] ~= nil then
         local f
         f = io.open("/etc/sysconfig/network-scripts/ifcfg-bond0", "w")
         if f then
            local s = omg.dumpTableToDelimiterList(networking.bond0,".","=")
            f:write(s)
            f:close()
         end
         if osVersion=="6" then
            os.execute("ln -f /etc/sysconfig/network-scripts/ifcfg-bond0 /etc/sysconfig/networking/devices")
         end
      elseif networking.bond0~=nil then
         if osVersion=="6" then
            os.execute("rm -f /etc/sysconfig/networking/devices/ifcfg-bond0")
         end
         os.execute("rm -f /etc/sysconfig/network-scripts/ifcfg-bond0")
      end

      if (newCentos and myOptions.merge==nil and myOptions.restore==nil) then
         omg.execute('nmcli connection reload')
         omg.execute('nmcli networking off')
         omg.execute('nmcli networking on')
      end

      if (newCentos) then
         mg.execute('nmcli dev connect eth0')
      end
   end
end

omg.runScript({}, arg, "OMG set network\n")
