-- 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 ipmi = require 'manufacture.ipmi.cmds.ImportImageToGpu'
local mc_ipmi = require 'ipmi'
local utils_file = require 'utils.file'
local client = require 'manufacture.client'
local context = require 'mc.context'
local log = require "mc.logging"

local cc = mc_ipmi.types.Cc
local MANAGER_ID<const> = 1

local ipmi_handler = {}

function ipmi_handler.import_image_to_gpu(req, ctx)
    local bpp = req.Bpp
    local path = req.Path
    local size = tostring(req.Length) .. "x" .. tostring(req.Width)

    if utils_file.check_real_path_s(path, '/tmp') ~= 0 then
        log:error('Input path is invalid.')
        return ipmi.ImportImageToGpuRsp.new(cc.DataNotAvailable)
    end

    local ok, res = client:PBmcDfxGPUToolImport(context.new(), {ManagerId = MANAGER_ID}, path, size, bpp)
    if not ok or not res or not res.Result then
        mc_ipmi.ipmi_operation_log(ctx, 'manufacture', "Import image to gpu failed.")
        return ipmi.ImportImageToGpuRsp.new(cc.UnspecifiedError)
    end

    mc_ipmi.ipmi_operation_log(ctx, 'manufacture', "Import image to gpu successfully.")
    return ipmi.ImportImageToGpuRsp.new(cc.Success)
end

return ipmi_handler