module("rsm_serials", package.seeall)
local sqlite3 = require("lsqlite3")
--includes
require("config/main_conf")
require("config/rsm_conf")
require("lsqlite3")
require("luamods/command")

function generateNewSerial()
    dbase = sqlite3.open( rsm_conf.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.ex(rsm_conf.rsmc_path.." GET: TAG_SITE_CFG")
    xx,yy = s:match("TAG_SITE_ID=\".+:(%x+):(%x+)\"")
    serial = "0x7F"..xx..yy.."01"
    return serial
end