#!/usr/bin/bash
#
# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. ALL RIGHTS RESERVED.
#
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES.
# SPDX-License-Identifier: LicenseRef-NVIDIA-Proprietary
#
source "$(dirname "$0")/_lib.sh"
trace "$@"
BDF=$(bdf_from_target "$1"); FIELD="$2"; VALUE="$3"

set_mlxconfig() {
    local assignment="$1"
    [[ -n "${DMS_BACKEND_TRACE:-}" ]] && \
        echo "mlxconfig-breakout-set: exec mlxconfig -d ${BDF} -y set ${assignment}" >&2
    trace "SET-EXEC mlxconfig -d ${BDF} -y set ${assignment}"
    mlxconfig_set "$BDF" "$assignment"
}

if [[ "$FIELD" =~ ^MODULE_LANES_M([0-9]+)_P([0-9]+)$ ]]; then
    MODULE="${BASH_REMATCH[1]}"
    PORT="${BASH_REMATCH[2]}"
    PORT_VALUE=$(printf '0x%x' "$PORT")
    IFS=',' read -r -a LANES <<< "$VALUE"
    for lane in "${LANES[@]}"; do
        lane="${lane//[[:space:]]/}"
        [ -n "$lane" ] || continue
        set_mlxconfig "MODULE_SPLIT_M${MODULE}[${lane}]=${PORT_VALUE}"
    done
    echo "${FIELD}=${VALUE}"
elif [[ "$FIELD" =~ ^MODULE_SPLIT_M([0-9]+)_P ]]; then
    FIELD_MODULE="${BASH_REMATCH[1]}"
    if ! [[ "$VALUE" =~ ^([0-9]+)x([0-9]+[gG])$ ]]; then
        tool_fail 1 "preset '${VALUE}': expected NxSpeedg format (e.g. 4x100g)"
    fi
    # Preset string (e.g. 4x100g): distribute TOTAL_LANES evenly across N_PORTS.
    # Lane count is derived from PMTM module_width (2^module_width lanes).
    N_PORTS="${BASH_REMATCH[1]}"
    (( N_PORTS > 0 && (N_PORTS & (N_PORTS - 1)) == 0 )) || \
        tool_fail 1 "preset '${VALUE}': port count must be a power of 2 (got ${N_PORTS})"
    TOTAL_LANES=$(detect_module_lane_count "$BDF" "$FIELD_MODULE") || \
        tool_fail 1 "preset '${VALUE}': could not determine lane count for module ${FIELD_MODULE}"
    (( TOTAL_LANES % N_PORTS == 0 )) || \
        tool_fail 1 "preset '${VALUE}': ${N_PORTS} ports not valid for ${TOTAL_LANES}-lane module"
    LANES_PER_PORT=$(( TOTAL_LANES / N_PORTS ))
    for (( port=1; port<=N_PORTS; port++ )); do
        START=$(( (port - 1) * LANES_PER_PORT ))
        for (( lane=START; lane<START+LANES_PER_PORT; lane++ )); do
            set_mlxconfig "MODULE_SPLIT_M${FIELD_MODULE}[${lane}]=${port}"
        done
    done
    echo "${FIELD}=${VALUE}"
else
    set_mlxconfig "${FIELD}=${VALUE}"
    echo "${FIELD}=${VALUE}"
fi
