-- Copyright (c) 2025 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 c_object_manage = require 'mc.orm.object_manage'

local port_mac = {}

function port_mac.update_mac_addr_from_db(orm_obj)
    local card = orm_obj.parent
    -- 不支持热插拔的网卡无需从数据库中恢复mac地址
    if not card or not card.HotPluggable then
        return
    end

    local db = c_object_manage.get_instance().per_db
    local network_port = db:select(db.NetworkPort):where({PortID = orm_obj.PortID,
        NetworkAdapterId = orm_obj.NetworkAdapterId}):first()
    local times = 0

    while not network_port and times < 20 do
        network_port = db:select(db.NetworkPort):where({PortID = orm_obj.PortID,
            NetworkAdapterId = orm_obj.NetworkAdapterId}):first()
        orm_obj:sleep_ms(1000)
        times = times + 1
    end

    if network_port then
        log:notice('set macaddr from database, mac = %s, port = %s', network_port.MACAddress, orm_obj.PortID)
        orm_obj.MACAddress = network_port.MACAddress
        orm_obj.PermanentMACAddress = network_port.MACAddress
    else
        log:notice('can not find macaddr from database, port = %s', orm_obj.PortID)
    end
end

return port_mac