-- 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 cjson = require 'cjson'

local m = {}

local REGEX_ROOT_CERT<const> = '/bmc/kepler/Managers/1/Certificates/(%d+)'
local INFT_ROOT_CERT<const> = 'bmc.kepler.CertificateService.Certificate'

function m.get_root_certificate_info(cert_path_list)
    local chain_info = cjson.json_object_new_array() -- cjson有序接口，生成的JSON对象数据保持与添加的顺序一致
    for _, cert_path in ipairs(cert_path_list) do
        local cert_id = string.match(cert_path, REGEX_ROOT_CERT)
        local ok, cert_obj = pcall(mdb.get_object, bus, cert_path, INFT_ROOT_CERT)
        if not ok then
            log:error('Get CA cert(id:%d) failed!', cert_id)
            error(cert_obj)
        end
        local tmp_root_cert = cjson.json_object_new_object()
        tmp_root_cert.CertId = cert_id
        tmp_root_cert.Issuer = cert_obj.Issuer
        tmp_root_cert.Subject = cert_obj.Subject
        tmp_root_cert.ValidNotBefore = cert_obj.ValidNotBefore
        tmp_root_cert.ValidNotAfter = cert_obj.ValidNotAfter
        tmp_root_cert.SerialNumber = cert_obj.SerialNumber
        chain_info[#chain_info + 1] = tmp_root_cert
    end
    return chain_info
end

return m
