-- 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: 获取BMC系统从启动到现在的运行时间(BMC重启后，时间会重新开始计算)
local utils = require 'mc.utils'
local utils_file = require 'utils.file'
local utils_core = require 'utils.core'
local log = require 'mc.logging'

local BMC_UPTIME_FILE <const> = "/proc/uptime" -- BMC从启动到现在的运行时间的保存文件

local m = {}

function m.get()
    local ret = utils_file.check_real_path_s(BMC_UPTIME_FILE, BMC_UPTIME_FILE) -- 路径合法性校验
    if ret ~= 0 then
        log:error('the file path of bmc uptime is invalid.')
        return
    end

    if not utils_core.is_file(BMC_UPTIME_FILE) then
        return
    end

    local file = utils_file.open_s(BMC_UPTIME_FILE, 'r')
    if file == nil then
        log:error('open the file of bmc uptime failed.')
        return
    end

    local content = file:read('*a')
    file:close()
    if content == nil or string.len(content) == 0 then
        log:error('read the bmc uptime from file failed.')
        return
    end

    local uptime_list = utils.split(content, " ")
    local uptime = tonumber(uptime_list[1]) -- 第1个时间为BMC系统从启动到现在的运行时间
    local time = math.floor(uptime + 0.5)   -- 四舍五入取整数

    -- 时间格式转换
    local day = time // (60 * 60 * 24)
    local hour = (time // (60 * 60)) % 24
    local min = (time // 60) % 60
    local sec = time % 60

    local time_format = string.format("%d days %.2dh:%.2dm:%.2ds", day, hour, min, sec)

    return time_format
end

return m
