-- 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_storage_common = {}
local mdb = require 'mc.mdb'
require 'ipmi'
local bs = require 'mc.bitstring'
local context = require 'mc.context'
local ipmi = require 'mc.ipmi'
local comp_code = ipmi.types.Cc

local bus_param

function test_storage_common.set_bus(bus)
    bus_param = bus
end

function test_storage_common.send_ipmi_core(ipmi_req)
    local bus = bus_param
    ipmi_req.Payload = ipmi_req.Payload .. '\x00'
    local ipmi_package = bs.new('<<_,_:2,DestNetFn:6,_:3/unit:8,Cmd,Payload/string>>')
    local req = ipmi_package:pack(ipmi_req)
    -- ctx打桩
    local channel_type = require 'mc.ipmi.enums'.ChannelType
    local cjson = require 'cjson'
    local ctx = cjson.encode({
        ChanType = channel_type.CT_ME:value(),
        Instance = 0,
        session = {
            user = {
                name = 'test'
            }
        },
        from = '\x11\x11\x11\x4B\xFF\x14\xB5' -- 前三个字节是端口, 后四个字节是ip地址
    })
    local ipmi_core = mdb.get_object(bus, '/bmc/kepler/IpmiCore', 'bmc.kepler.IpmiCore')

    local resp = ipmi_core:Route(context.new(), req, ctx)
    local completion_code = string.unpack('B', resp)
    if completion_code ~= comp_code.Success then
        return false, nil
    end
    return true, string.sub(resp, 2, -1)
end

function test_storage_common.send_ipmi(data)
    local format = "0x(%w+)"
    local res = ''
    local index = 0
    local net_fn, cmd
    for word in string.gmatch(data, format) do
        if index == 0 then
            net_fn = tonumber(word, 16)
        elseif index == 1 then
            cmd = tonumber(word, 16)
        else
            res = res .. string.char(tonumber(word, 16))
        end
        index = index + 1
    end
    local req = { DestNetFn = net_fn, Cmd = cmd, Payload = res }
    return test_storage_common.send_ipmi_core(req)
end

return test_storage_common
