-- 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 M = {}

local function is_have_user_mgmt(privileges)
    for _, value in ipairs(privileges) do
        if value == 'UserMgmt' then
            return true
        end
    end

    return false
end

function M.get_redfish_session_members(Context)
    local sessions = {}
    local path = '/bmc/kepler/SessionService/Sessions'
    local interface = 'bmc.kepler.SessionService.Session'
    local ok, session_collection_objs = pcall(function ()
        return mdb.get_sub_objects(bus, path, interface)
    end)
    if not ok then
        log:error('get session objects failed')
        return sessions
    end
    for _, obj in pairs(session_collection_objs) do
        if tonumber(obj['AccountId']) < 2 or
            (tonumber(obj['AccountId']) > 21 and tonumber(obj['AccountId']) < 1000) then
            goto continue
        end
        local session_path = '/redfish/v1/SessionService/Sessions/' .. obj['SessionId']
        if is_have_user_mgmt(Context.Privilege) or Context.UserName == obj.UserName then
            sessions[#sessions + 1] = session_path
        end
        ::continue::
    end

    return sessions
end

return M
