-- 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 test_write_bdf = {}
local bs = require 'mc.bitstring'
local log = require 'mc.logging'
require 'ipmi'
local test_bios_common = require 'test_bios_common'
local function send_ipmi(data)
    return test_bios_common.send_ipmi(data)
end

local WRITE_BIOS_DATA_RSP = '<<ManufactureId:3/unit:8>>'

local function get_bios_property(bus, name, system_id, prop_name)
    return bus:call('bmc.kepler.bios', '/bmc/kepler/Systems/' .. system_id .. '/' .. name,
        'org.freedesktop.DBus.Properties', 'Get', 'ss', 'bmc.kepler.Systems.' .. name, prop_name):value()
end

function test_write_bdf.test_send_bdf(bus)
    -- 只有一帧
    local ok, rsp = send_ipmi('0x06 0x58 0xc6 0x01 0x01 0x01 0x31 0x32 0x33 0x34 0x35')
    assert(ok == true)
    if ok then
        local data = bs.new(WRITE_BIOS_DATA_RSP):unpack(rsp)
        local bdf_data = get_bios_property(bus, 'Bios', 1, 'PcieCardBDF')
        assert(data.ManufactureId == 0x0007DB)
        assert(bdf_data == '12345')
    end

    -- 有三帧
    ok, rsp = send_ipmi('0x06 0x58 0xc6 0x03 0x01 0x01 0x31 0x32 0x33 0x34 0x35')
    assert(ok == true)
    if ok then
        local data = bs.new(WRITE_BIOS_DATA_RSP):unpack(rsp)
        assert(data.ManufactureId == 0x0007DB)
    end

    ok, rsp = send_ipmi('0x06 0x58 0xc6 0x03 0x02 0x01 0x31 0x32 0x33 0x34 0x35')
    assert(ok == true)
    if ok then
        local data = bs.new(WRITE_BIOS_DATA_RSP):unpack(rsp)
        assert(data.ManufactureId == 0x0007DB)
    end

    ok, rsp = send_ipmi('0x06 0x58 0xc6 0x03 0x03 0x01 0x31 0x32 0x33 0x34 0x35')
    assert(ok == true)
    if ok then
        local data = bs.new(WRITE_BIOS_DATA_RSP):unpack(rsp)
        local bdf_data = get_bios_property(bus, 'Bios', 1, 'PcieCardBDF')
        assert(data.ManufactureId == 0x0007DB)
        assert(bdf_data == '123451234512345')
    end
end

return test_write_bdf