-- 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 index = string.match(PropertyName, 'LdapGroups/(%d)/')
if index == nil then
    return
end

local GroupName   = ReqBody.LdapGroups[index+1].GroupName
local GroupDomain = ReqBody.LdapGroups[index+1].GroupDomain

-- 没有Domain就不需要校验了
if GroupDomain == nil then
    return
end

-- 当有GroupName且不为空字符串时（删除动作），才校验GroupName
if GroupName == nil or GroupName == "" then
    return
end

local cn_pos = string.find(GroupDomain, 'CN=', 1)
local pos = string.find(GroupDomain, ',', 1)
local name_str
if cn_pos == nil then
    name_str = GroupName or ''
else
    if pos == nil then
        pos = string.len(GroupDomain)
    else
        pos = pos - 1
    end
    name_str = string.sub(GroupDomain, cn_pos + 3, pos)
end

if GroupName ~= name_str then
    local err = custom_messages.GroupNameMismatch('CN', 'LdapGroups/' .. index .. '/GroupName')
    err.RelatedProperties = {'#/LdapGroups/' .. index .. '/GroupName'}
    error(err)
end