-- 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 class = require 'mc.class'
local sr_upgrade_base = require 'sr_upg_service.class.sr_upgrade'
local std_smbus_cfg = require 'protocol.std_smbus'
local log = require 'mc.logging'
local skynet = require 'skynet'
local CHIP_BUFFER_LEN <const> = 32

local sr_upgrade = class(sr_upgrade_base)

function sr_upgrade:init()
    sr_upgrade.super.init(self)
    self.std_smbus = std_smbus_cfg.new(self.mds_obj['WriteProtectChip'], CHIP_BUFFER_LEN)
    skynet.fork(function ()
        local retry_times = 5
        local ok, err
        for _ = 1, retry_times do
            -- 默认关闭UBNIC卡的写保护,需要初始化时打开
            ok, err = pcall(function()
                return self.std_smbus:GetCapability()
            end)
            if not ok then
                log:error('[DPU] get capability failed, error:%s', err)
                return
            end
            ok, err = self:write_protect_open()
            if ok then
                log:notice("sdi open write protect successfully")
                break
            end
            log:error("sdi open write protect failed, err ir %s", err)
            skynet.sleep(100)
        end
    end)
end

-- EEPROM写保护，打开
function sr_upgrade:write_protect_open()
    return pcall(function ()
        self.std_smbus:WriteProtext(1)
    end)
end

-- EEPROM写保护，关闭
function sr_upgrade:write_protect_close()
    return pcall(function ()
        self.std_smbus:WriteProtext(0)
    end)
end

return sr_upgrade