-- 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 old_groups = ProcessingFlow[2].Destination.Groups
local is_group_exist = {false, false, false, false, false}
for _, group in ipairs(old_groups) do
    -- 示例: 从/bmc/kepler/AccountService/RemoteGroups/LDAP1_2中获取LDAP后的1和2
    local controller_id, group_id = string.match(group, '.*/LDAP(%d+)_(%d+)')
    if controller_id == Uri.controllerid then
        is_group_exist[tonumber(group_id)] = true
    end
end

local op_type = {'modify', 'modify', 'modify', 'modify', 'modify'}
for i = 1, 5 do
    -- 使用ReqBodyOriginal原始输入来判断，避免校验不通过造成误判断
    local group_name = (ReqBodyOriginal.LdapGroups[i] or {}).GroupName
    local group_domain = (ReqBodyOriginal.LdapGroups[i] or {}).GroupDomain

    local cn_pos
    if group_domain ~= nil then
        cn_pos = string.find(group_domain, 'CN=', 1)
    end

    -- Ldap组不存在且不新建Ldap组时操作类型为none
    if not ReqBodyOriginal.LdapGroups[i] or
        cjson.json_object_is_equal(ReqBodyOriginal.LdapGroups[i], cjson.json_object_new_object()) or
        (not is_group_exist[i] and (group_name == '' or group_name == null)) then
        op_type[i] ='none'
    elseif not is_group_exist[i] and -- 组不存在，有非空组名或者有带了CN的GroupDomain即为新建
        ((group_name ~= null and group_name ~= '' and group_name ~= nil) or cn_pos ~= nil) then
        op_type[i] = 'add'
    elseif not is_group_exist[i] and -- ldapgroup组不存在，且无非空组名且无带了CN的GroupDomain即为视为属性不合法
        ((group_name == nil or group_name == null or group_name == '') and cn_pos == nil) then
        local info = "MemberId." .. tostring(i-1) .. '.GroupName'
        error(custom_messages.PropertyItemMissing(info))
    elseif is_group_exist[i] and (group_name == '' or group_name == null) then -- 不传用户名只修改属性，传递空用户名才是删除
        op_type[i] = 'delete'
    end
end

return op_type