-- 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 context = require 'mc.context'
local OBJECT_PROPERTIES_INTERFACE<const> = 'bmc.kepler.Object.Properties'
--Bios 所在服务
local BIOS_MDB_SERVICE <const> = 'bmc.kepler.bios'
--Bios 资源树接口
local BIOS_MDB_INTF <const> = 'bmc.kepler.Systems.Bios'

local m = {}

local function get_sysid(path)
    local sysid = -1
    local err, rsp = bus:pcall(BIOS_MDB_SERVICE, path, OBJECT_PROPERTIES_INTERFACE, 'GetAllWithContext', 'a{ss}s',
        context.get_context() or context.new(), OBJECT_PROPERTIES_INTERFACE)
    if not err then
        local identifier = rsp.ObjectIdentifier and rsp.ObjectIdentifier:value()
        if identifier then
            sysid = identifier[1]
        end
    end
    return sysid
end

local function get_system_bios_list(input)
    local bios_list = {}
    if #input ~= 0 then
        -- input[1]代表 -s 传的参数
        bios_list = mdb.get_sub_objects(bus, '/bmc/kepler/Systems/'.. input[1], BIOS_MDB_INTF)
    else
        bios_list = mdb.get_sub_objects(bus, '/bmc/kepler/Systems', BIOS_MDB_INTF, 2)
    end
    return bios_list
end

function m.get_hosttype()
    return mdb.get_object(bus, '/bmc/kepler/Managers/1/Multihost',
        'bmc.kepler.Managers.Multihost').HostType
end

function m.clear_cmos(input)
    local objs = {}
    local bios_list = get_system_bios_list(input)
    local ctx = context.get_context_or_default()
    for _, v in pairs(bios_list) do
        objs[#objs + 1] = {}
        objs[#objs].sysid = get_sysid(v.path)
        objs[#objs].Bios = v
    end

    table.sort(objs, function(a, b)
        return a.sysid < b.sysid
    end)

    for _, v in ipairs(objs) do
        local _, err = pcall(function ()
            v.Result = v.Bios:ClearCmos(ctx).Result
        end)
        if err and err.name == 'InsufficientPrivilege' then
            v.Error = err.format
        end
        v.Bios = nil
    end
    return objs
end

return m