-- Copyright (c) 2024 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.


local log = require 'mc.logging'
local ini_parser = require 'mc.v2_persistence'

local parser_cfg = {}

local function cfg_new(name, data)
    ---@class UpdateCfg table @某一PCIe卡槽位的信息
    ---@field component_id number @ComponentID
    local cfg = {
        name = name,
        component_id = tonumber(data.ComponentID),
        component_id_ex = tonumber(data.ComponentIDEx),
        board_id = tonumber(data.BoardID)
    }
    return cfg
end

-- prepare阶段框架会下发解包的update.cfg路径，解析文件内容，获取每个Firmware的配置
function parser_cfg.get_cfgs(path)
    local cfgs = {}
    if not path then
        log:error("Cfg path is nil")
        return cfgs
    end

    log:info("get cfg path=%s", path)
    local data = ini_parser.load_file(path)
    if not data.Basic or not data.Basic.Version then
        log:error('Get Basic Version failed')
        return cfgs
    end
    local file_num = tonumber(data.Firmware.FileNum)
    if file_num == 0 then
        log:error('Update file num is invalid')
        return cfgs
    end
    for i = 1, file_num - 1 do -- 第1个Firmware指的就是配置文件，从1开始
        local name = 'Firmware' .. i
        if data[name] then
            cfgs[name] = cfg_new(name, data[name])
            log:info("Get Firmware, name=%s", name)
        end
    end
    return cfgs
end

return parser_cfg