-- 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 file_utils = require 'utils.file'
local core_utils = require 'utils.core'
local mdb_service = require 'mc.mdb.mdb_service'
local log = require 'mc.logging'

local m = {}

function m.unique_array(arr, default)
    if arr == nil then
        return default
    end

    local set = {}
    local res = {}
    for _, v in ipairs(arr) do
        if not set[v] then
            res[#res + 1] = v
            set[v] = true
        end
    end
    return res
end

function m.is_import_permitted(type, content, file_type, perproty_name, result)
    if type ~= 'URI' then
        return true
    end

    local pattern_collection = {
        ['pub'] = "^((https|sftp|nfs|cifs|scp)://.{1,1000}|/tmp/.{1,246})\\.pub$",
        ['cert'] = "^((https|sftp|nfs|cifs|scp)://.{1,1000}|/tmp/.{1,246})\\.(crt|cer|cert|pem|p12|pfx|der)$",
        ['tab'] = "^((https|sftp|nfs|cifs|scp)://.{1,1000}|/tmp/.{1,246})\\.tab$",
        ['crl'] = "^((https|sftp|nfs|cifs|scp)://.{1,1000}|/tmp/.{1,246})\\.crl$"
    }
    local error_collection = {
        ['pub'] = custom_messages.PublicKeyImportFailed(),
        ['cert'] = custom_messages.CertImportFailed(),
        ['tab'] = custom_messages.InvalidPath("******", perproty_name),
        ['crl'] = custom_messages.CrlImportFailed()
    }
    if not core_utils.g_regex_match(pattern_collection[file_type], content) then
        error(base_messages.PropertyValueFormatError("******", perproty_name))
    end

    if content:sub(1,1) ~= '/' then
        return true
    end

    if not core_utils.is_file(content) then
        error(error_collection[file_type])
    end

    if file_utils.check_real_path_s(content, "/tmp") ~= 0 then
        error(error_collection[file_type])
    end

    if result then
        return true
    end
    error(custom_messages.NoPrivilegeToOperateSpecifiedFile())
end

function m.is_valid_path(path)
    local ok, rsp = pcall(mdb_service.is_valid_path, bus, path)
    if not ok then
        log:info('Invalid Path, err(%s)', rsp.message)
        error(rsp)
    end

    return rsp.Result
end

function m.is_valid_system_id(id)
    local path = '/bmc/kepler/Systems/' .. id

    local ok, rsp = pcall(mdb_service.is_valid_path, bus, path)
    if not ok then
        log:error('Invalid SystemId(%s), err(%s)', id, rsp.message)
        error(rsp)
    end

    return rsp.Result
end

return m
