-- 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.

-- Description: file的相关工具
local file_sec = require 'utils.file'
local vos = require 'utils.vos'
local log = require 'mc.logging'
local utils = require 'mc.utils'
local file_util = {}

function file_util.decompress_file(src, dest)
    utils.secure_tar_unzip(
        src,
        dest,
        0x6400000, -- 最大解压限制100M
        1024
    )
end

function file_util.copy_file(src, dest_file)
    if not vos.get_file_accessible(src) then
        log:info('[bios]copy file fail: src not accessible')
        return false
    end

    for _ = 1, 3 do
        local res = file_sec.copy_file_s(src, dest_file)
        if res == 0 then
            return true
        end
    end
    log:error('[bios]copy file fail: copy file fail')
    return false
end

function file_util.get_file_data(path)
    if not vos.get_file_accessible(path) then
        return nil
    end
    local file = file_sec.open_s(path, 'r')
    if not file then
        return nil
    end

    local file_string = utils.close(file, pcall(file.read, file, "*a"))
    return file_string
end

function file_util.write_file_data(path, data)
    local file = file_sec.open_s(path, 'wb')
    if not file then
        return false
    end
    return utils.close(file, pcall(file.write, file, data))
end

return file_util