-- 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 log = require 'mc.logging'
local singleton = require 'mc.singleton'
local utils = require 'mc.utils'
local vos = require 'utils.vos'
local file_sec = require 'utils.file'

local fpga_package = {}
fpga_package.__index = fpga_package

local UPGRADE_FPGA_TMP_DIR = '/data/backup/fpga/tmp'
local UPGRADE_FPGA_GOLD_DIR = '/data/backup/fpga/gold'

function fpga_package.new(db)
    utils.mkdir_with_parents(UPGRADE_FPGA_TMP_DIR, utils.S_IRWXU | utils.S_IRGRP | utils.S_IXGRP)
    utils.mkdir_with_parents(UPGRADE_FPGA_GOLD_DIR, utils.S_IRWXU | utils.S_IRGRP | utils.S_IXGRP)
    return setmetatable({
        db = db,
        UpgradeFpgaTmpDir = UPGRADE_FPGA_TMP_DIR,
        UpgradeFpgaGoldDir = UPGRADE_FPGA_GOLD_DIR
    }, fpga_package)
end

function fpga_package:cache_fpga_hpm(hpm_src_path, hpm_dst_dir)
    if not hpm_src_path or not vos.get_file_accessible(hpm_src_path)  then
        log:error('[fpga]fpga package: hpm src path is no accessible')
        return
    end

    local hpm_dst_path = hpm_dst_dir .. '/fpga.hpm'
    if vos.get_file_accessible(hpm_dst_path) then
        utils.remove_file(hpm_dst_path)
    end

    utils.mkdir_with_parents(hpm_dst_dir, utils.S_IRWXU | utils.S_IRGRP | utils.S_IXGRP)
    local backup_res = -1
    for _ = 1, 3 do
        backup_res = file_sec.copy_file_s(hpm_src_path, hpm_dst_path)
        if backup_res == 0 then
            break
        end
    end

    if backup_res ~= 0 then
        log:error('[fpga]fpga package: cache back up hpm fail, err:%s', backup_res)
        return
    end
    utils.chmod(hpm_dst_path, utils.S_IRUSR)
    log:notice('[fpga]fpga package: backup %s success', hpm_dst_path)
    return
end

function fpga_package:remove_tmp_fpga_hpm()
    local tmp_path = self.UpgradeFpgaTmpDir .. '/fpga.hpm'
    if vos.get_file_accessible(tmp_path) then
        utils.remove_file(tmp_path)
    end
end

return singleton(fpga_package)
