-- 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 image_uri = ReqBody.ImageURI
local signal_uri = ReqBody.SignalURI

local function throw_error(name)
    local err = base_messages.PropertyValueFormatError('******', name)
    err.RelatedProperties = {'#/' .. name}
    error(err)
end

local function validate_length(uri)
    local filename = string.match(uri, '/([^/]+)$')
    if filename == nil or filename == '' or string.len(filename) > 200 then
        throw_error(uri == image_uri and 'ImageURI' or 'SignalURI')
    end
end

local function validate(target, accept_list)
    if target then
        for _, v in ipairs(accept_list) do
            if target == v then
                return true
            end
        end
    end
    return false
end

-- ImageURI文件名长度不超过200
validate_length(image_uri)

local protocol, body, format = string.match(image_uri, '(.*)://(.*)%.(.*)')
if not protocol and ReqBody.ImageType == 'SP' then    -- 匹配失败，校验SP升级二段式 image
    protocol, body = string.match(image_uri, '(.*)://(.*)')
    if body == nil or string.len(body) > 1000 then
        throw_error('ImageURI')
    end
    if not validate(protocol, {'nfs', 'cifs'}) then
        throw_error('ImageURI')
    end
end

-- ImageURI中间长度不能超过1000
if body == nil or string.len(body) > 1000 then
    throw_error('ImageURI')
end

if ReqBody.ImageType == 'Firmware' then
    -- SignalURI文件名长度不超过200
    validate_length(signal_uri)

    -- 固件升级 protocol只支持https, sftp, nfs, cifs, scp, file
    -- 后缀只支持zip
    if not validate(protocol, {'https', 'sftp', 'nfs', 'cifs', 'scp', 'file'}) or
        not validate(format, {'zip'}) then
        throw_error('ImageURI')
    end

    -- 固件升级 才进行签名文件校验
    local signal_protocol, signal_body, signal_format =
        string.match(signal_uri, '(.*)://(.*)%.(.*)')

    -- SignalURI中间长度不能超过1000
    if signal_body == nil or string.len(signal_body) > 1000 then
        throw_error('SignalURI')
    end
    -- protocol只支持https, sftp, nfs, cifs, scp, file
    -- 后缀只支持asc, p7s
    if not validate(signal_protocol, {'https', 'sftp', 'nfs', 'cifs', 'scp', 'file'}) or
        not validate(signal_format, {'asc', 'p7s'}) then
        throw_error('SignalURI')
    end
else
    -- SP升级 protocol只支持nfs, cifs
    if not validate(protocol, {'nfs', 'cifs'}) then
        throw_error('ImageURI')
    end
end

return true

