
local sqlite3 = require("lsqlite3")
--includes
require("lsqlite3")

rsmc_path = "/usr/bin/rsmc"
serial_db_path = "/srv/http/database/rsm_serials.db"

function command_exec(cmd)
  local f = io.popen(cmd) 
  value = f:read("*a") or "none"
  f:close()
  return value
end

function generateNewSerial()
  dbase = sqlite3.open( serial_db_path )
  
  for rows in dbase:urows( [[ SELECT serial_num FROM 'serials' WHERE desc='last' ]]) do
    serial = rows
  end
  if (tonumber(serial) == 0) then
    serial = generateFirstSerial()
  end
  
  newSerial = tonumber(serial)
  newSerial = newSerial + 1
  newSerial = string.format("0x%08X", newSerial)
  dbase:exec([[ UPDATE 'serials' SET serial_num=']]..newSerial..[[' WHERE desc='last' ]])
  return serial
end

-- No serial exists, create one in the format "7Fxxyy01"
-- xx:yy are the last two bytes of the site id
function generateFirstSerial()
  s = command_exec(rsmc_path.." GET: TAG_SITE_CFG")
  xx,yy = s:match("TAG_SITE_ID=\".+:(%x+):(%x+)\"")
  serial = "0x7F"..xx..yy.."01"
  return serial
end

