-- 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 m = {}

function m.parse_mac_addr(mac_addr)
    if not mac_addr:match('^%x%x:%x%x:%x%x:%x%x:%x%x:%x%x$') then
        log:error('mac addr is invalid: %s', mac_addr)
        return {false}
    end

    local broadcast_num = 0xFF
    local mac = ''
    for part in mac_addr:gmatch('[^:]+') do
        broadcast_num = broadcast_num & tonumber('0x' .. part)
        mac = mac .. string.char(tonumber('0x' .. part))
    end

    -- 判断是否为广播mac
    if broadcast_num == 0xFF then
        log:error('%s is broadcast mac', mac_addr)
        return {false}
    end

    -- 通过mac地址第一段判断是否为多播mac
    local multicast_num = tonumber('0x' .. mac_addr:match('[^:]+'))
    if multicast_num & 0x01 == 1 then
        log:error('%s is multicast mac', mac_addr)
        return {false}
    end

    return {true, mac}
end

function m.combine_mac_addr(mac)
    local mac_addr = ''
    for i = 1, #mac do
        mac_addr = mac_addr .. string.format('%02X', string.byte(mac, i)) .. ':'
    end

    return mac_addr:sub(1, #mac_addr - 1)
end

return m