-- 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 GroupFolder = ReqBody.LdapGroups[index+1].GroupFolder
local GroupDomain = ReqBody.LdapGroups[index+1].GroupDomain

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

-- 当有GroupFolder时，校验GroupFolder
if GroupFolder == nil then
    return
end

local cn_pos = string.find(GroupDomain, 'CN=', 1)
local pos = string.find(GroupDomain, ',', 1)
local remain_str

if cn_pos == nil then
    remain_str = GroupDomain
else
    if pos == nil then
        pos = string.len(GroupDomain)
        remain_str = ''
    else
        -- 此处截取+1是为了跳过","
        remain_str = string.sub(GroupDomain, pos + 1, string.len(GroupDomain))
    end
end

-- 此时remain_str期望为GroupDomain去掉"CN=***,"的部分
local dc_pos = string.find(remain_str, 'DC=', 1)
local folder_str
if not dc_pos then
    folder_str = remain_str
elseif dc_pos == 1 or dc_pos == 2 then
    folder_str = ''
else
    -- 此处截取-2是为了跳过"DC"和前面的","
    folder_str = string.sub(remain_str, 1, dc_pos - 2)
end

if GroupFolder ~= folder_str then
    local err = custom_messages.PropertyValueMismatch('OU', 'GroupDomain', 'LdapGroups/' .. index .. '/GroupFolder')
    err.RelatedProperties = {'#/LdapGroups/' .. index .. '/GroupFolder'}
    error(err)
end