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

config={}

helpString=omg.getHelpString(arg[0],"print OMG product info\n")
helpString=helpString .. "\t--fullName\tjust print the full namegives a list config set names\n"
helpString=helpString .. "\t--all\tprint all article info available\n"

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

productCode=execute('licinfo -dw | grep 0ProductCode | cut -d ":" -f 4')

jsonString=readAll("/usr/bin/omghw.json")
omghw=json.decode(jsonString)

myOptions=omg.splitCommandlineString(arg)

if myOptions.fullName~=nil then
   if productCode~=nil then
      for k,v in pairs(omghw) do
         if v.ProductCode==productCode then
            print(v.LicenseName)
            break
         end
      end
   else
       hwArticleNumber=execute('i2cinfo -l 2>&1 | head -n 1 | cut -d "," -f 7')
       if hwArticleNumber~=nil then
           for k,v in pairs(omghw) do
               if v.PartNo==hwArticleNumber then
                   print(v.LicenseName)
                   break
               end
           end
       end
   end
end

if myOptions.all~=nil then
   if productCode~=nil then
      for k,v in pairs(omghw) do
         if v.ProductCode==productCode then
            config=v
            break
         end
      end
   else
       hwArticleNumber=execute('i2cinfo -l 2>&1 | head -n 1 | cut -d "," -f 7')
       if hwArticleNumber~=nil then
           for k,v in pairs(omghw) do
               if v.PartNo==hwArticleNumber then
                   config=v
                   break
               end
           end
       end
   end
end


omg.runScript(config,arg,"print OMG product info\n")

