#!/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
#
# mlxconfig tool wrapper — REAL hardware version
# Calls actual mlxconfig for GET (query) and SET operations.
# Sources shared value maps from tools/ dir.

source "$(dirname "$0")/_lib.sh"
trace "$@"

# Source shared value maps (relative to DMS root)
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
source "$SCRIPT_DIR/_value_maps.sh" 2>/dev/null || source "$SCRIPT_DIR/../_value_maps.sh"

OP="$1"; shift
TARGET="$1"; shift
BDF=$(bdf_from_target "$TARGET")

# Read Current (offset 1) or Next Boot (offset 0), matching indexed names literally.
query_param_value() {
    local query="$1" param="$2" tail_offset="$3"

    awk -v param="$param" -v tail_offset="$tail_offset" '
        {
            name = $1
            if (name == "*")
                name = $2
            else
                sub(/^\*/, "", name)
            if (name == param) {
                print $(NF - tail_offset)
                exit
            }
        }
    ' <<< "$query"
}

if [[ "$OP" == "GET" || "$OP" == "GET-NEXT" ]]; then
    QUERY=$(mlxconfig_query "$BDF" "$@")
    PENDING_SUFFIX=""
    if [[ "$OP" == "GET-NEXT" ]]; then
        PENDING_SUFFIX="-pending"
    fi
    for PARAM in "$@"; do
        # -e output: Name Default Current NextBoot
        # GET: current running value = $(NF-1)
        # GET-NEXT: next-boot value = $NF
        if [[ "$OP" == "GET" ]]; then
            RAW=$(query_param_value "$QUERY" "$PARAM" 1)
        else
            RAW=$(query_param_value "$QUERY" "$PARAM" 0)
        fi
        if [[ -z "$RAW" ]]; then
            continue
        fi
        RAW="${RAW%%(*}"
        LEAF_NAME="${LEAF[$PARAM]:-$PARAM}"
        MAPPED="${REV[$PARAM:$RAW]:-$RAW}"
        echo "${LEAF_NAME}${PENDING_SUFFIX}=${MAPPED}"
        case "$PARAM" in
            NUM_OF_PLANES_P*) echo "planes${PENDING_SUFFIX}=${MAPPED}" ;;
            MODULE_LANES_M*_P*) echo "lanes${PENDING_SUFFIX}=${MAPPED}" ;;
            MODULE_SPLIT_M*_P*) echo "preset${PENDING_SUFFIX}=${MAPPED}" ;;
        esac
    done
elif [[ "$OP" == "SET" || "$OP" == "SET-BATCH" ]]; then
    SET_ARGS=()
    PARAMS=()
    VALUES=()
    RAW_VALUES=()
    NUMERIC_COMPARE=()
    declare -A SEEN_SET_VALUES=() SEEN_SET_INDICES=()
    REQUEST_INDICES=()
    REQUEST_LANES=()
    VERIFIED=()
    # Bound total lane expansion across all requests before any hardware write.
    MAX_EXPANDED_LANES=4096
    EXPANDED_LANES=0
    MAX_SHELL_UINT=9223372036854775807
    ALL_PORTS_ID=255

    normalize_uint() {
        local value="$1" limit="$2"

        [[ "$value" =~ ^[0-9]+$ ]] || return 1
        value="${value#"${value%%[!0]*}"}"
        value="${value:-0}"
        (( ${#value} <= ${#limit} )) || return 1
        if (( ${#value} == ${#limit} )) && [[ "$value" > "$limit" ]]; then
            return 1
        fi
        NORMALIZED_UINT="$value"
    }

    report_error() {
        # The executor captures stdout; keep the reason available with the batch report.
        if [[ "$OP" == "SET-BATCH" ]]; then
            echo "Error: $*"
        else
            echo "Error: $*" >&2
        fi
    }

    # Add one real mlxconfig assignment, rejecting conflicting duplicates before
    # mlxconfig is invoked. Identical duplicates are harmless and are emitted once.
    append_set_arg() {
        local param="$1" requested="$2" mapped="$3" numeric_compare="${4:-false}"

        if [[ -n "${SEEN_SET_VALUES[$param]+set}" ]]; then
            if [[ "${SEEN_SET_VALUES[$param]}" == "$mapped" ]]; then
                REQUEST_PARAM_INDICES+=" ${SEEN_SET_INDICES[$param]}"
                return 0
            fi
            report_error "conflicting mlxconfig values for ${param}: ${SEEN_SET_VALUES[$param]} vs ${mapped}"
            return 1
        fi
        SEEN_SET_VALUES["$param"]="$mapped"
        SEEN_SET_INDICES["$param"]="${#PARAMS[@]}"
        REQUEST_PARAM_INDICES+=" ${#PARAMS[@]}"
        VERIFIED+=(0)
        SET_ARGS+=("${param}=${mapped}")
        PARAMS+=("$param")
        VALUES+=("$requested")
        RAW_VALUES+=("$mapped")
        NUMERIC_COMPARE+=("$numeric_compare")
    }

    for PAIR in "$@"; do
        REQUEST_PARAM_INDICES=""
        PARAM="${PAIR%%=*}"
        VALUE="${PAIR#*=}"

        # `lanes` is a friendly DMS leaf, not a real firmware parameter. Expand
        # MODULE_LANES_M<m>_P<p>=l1,l2 into the MODULE_SPLIT array assignments
        # consumed by mlxconfig, while keeping them in this same SET invocation.
        if [[ "$PARAM" =~ ^MODULE_LANES_M([0-9]+)_P([0-9]+)$ ]]; then
            MODULE="${BASH_REMATCH[1]}"
            PORT="${BASH_REMATCH[2]}"
            if ! normalize_uint "$PORT" "$ALL_PORTS_ID"; then
                report_error "invalid MODULE_LANES port ${PORT}"
                exit 1
            fi
            # MODULE_SPLIT byte values are hexadecimal, even without a 0x prefix.
            printf -v PORT_VALUE '0x%x' "$NORMALIZED_UINT"
            if ! [[ "$VALUE" =~ ^[[:space:]]*[0-9]+[[:space:]]*(\.\.[[:space:]]*[0-9]+[[:space:]]*)?(,[[:space:]]*[0-9]+[[:space:]]*(\.\.[[:space:]]*[0-9]+[[:space:]]*)?)*$ ]]; then
                report_error "MODULE_LANES requires numeric lanes or ascending ranges separated by commas"
                exit 1
            fi
            IFS=',' read -r -a LANES <<< "$VALUE"
            for LANE in "${LANES[@]}"; do
                LANE="${LANE//[[:space:]]/}"
                FIRST="${LANE%%..*}"
                LAST="${LANE##*..}"
                if ! normalize_uint "$FIRST" "$MAX_SHELL_UINT"; then
                    report_error "invalid lane ${FIRST}"
                    exit 1
                fi
                FIRST="$NORMALIZED_UINT"
                if ! normalize_uint "$LAST" "$MAX_SHELL_UINT"; then
                    report_error "invalid lane ${LAST}"
                    exit 1
                fi
                LAST="$NORMALIZED_UINT"
                if (( FIRST > LAST || LAST - FIRST >= MAX_EXPANDED_LANES - EXPANDED_LANES )); then
                    report_error "lane ranges must be ascending and expand to at most ${MAX_EXPANDED_LANES} lanes in total"
                    exit 1
                fi
                (( EXPANDED_LANES += LAST - FIRST + 1 ))
                for (( LANE_INDEX=FIRST; ; LANE_INDEX++ )); do
                    append_set_arg "MODULE_SPLIT_M${MODULE}[${LANE_INDEX}]" "$PORT_VALUE" \
                        "$PORT_VALUE" true || exit 1
                    (( LANE_INDEX == LAST )) && break
                done
            done
            REQUEST_INDICES+=("$REQUEST_PARAM_INDICES")
            REQUEST_LANES+=("$VALUE")
            continue
        fi

        MAPPED="${FWD[$PARAM:$VALUE]:-$VALUE}"
        [[ -n "${DMS_BACKEND_TRACE:-}" ]] && \
            echo "mlxconfig-wrapper: SET input ${PARAM}=${VALUE} mapped=${MAPPED}" >&2
        trace "SET-MAP target=${TARGET} bdf=${BDF} param=${PARAM} value=${VALUE} mapped=${MAPPED}"
        append_set_arg "$PARAM" "$VALUE" "$MAPPED" || exit 1
        REQUEST_INDICES+=("$REQUEST_PARAM_INDICES")
        REQUEST_LANES+=("")
    done
    [[ -n "${DMS_BACKEND_TRACE:-}" ]] && \
        echo "mlxconfig-wrapper: exec ${MLXCONFIG_BIN:-mlxconfig} -d ${BDF} -y set ${SET_ARGS[*]}" >&2
    trace "SET-EXEC ${MLXCONFIG_BIN:-mlxconfig} -d ${BDF} -y set ${SET_ARGS[*]}"
    mlxconfig_set "$BDF" "${SET_ARGS[@]}" || exit $?

    QUERY_RC=0
    QUERY=$(mlxconfig_query "$BDF" "${PARAMS[@]}") || QUERY_RC=1
    if (( QUERY_RC != 0 )); then
        report_error "mlxconfig SET readback query failed for one or more parameters"
    fi
    if [[ -n "${DMS_BACKEND_TRACE:-}" ]]; then
        echo "mlxconfig-wrapper: readback query ${MLXCONFIG_BIN:-mlxconfig} -d ${BDF} -e q ${PARAMS[*]}" >&2
        echo "$QUERY" | sed 's/^/mlxconfig-wrapper: readback /' >&2
    fi
    trace "SET-READBACK-QUERY ${MLXCONFIG_BIN:-mlxconfig} -d ${BDF} -e q ${PARAMS[*]}"
    RC=$QUERY_RC
    for i in "${!PARAMS[@]}"; do
        PARAM="${PARAMS[$i]}"
        VALUE="${VALUES[$i]}"
        RAW_EXPECTED="${RAW_VALUES[$i]}"
        LEAF_NAME="${LEAF[$PARAM]:-$PARAM}"
        # Compare the first output field literally. Regex matching is incorrect
        # for indexed parameters such as MODULE_SPLIT_M0[4].
        RAW=$(query_param_value "$QUERY" "$PARAM" 0)
        RAW="${RAW%%(*}"
        if [[ -z "$RAW" ]]; then
            report_error "mlxconfig SET readback missing Next Boot for ${PARAM}"
            RC=1
            continue
        fi

        if [[ "${NUMERIC_COMPARE[$i]}" == "true" ]]; then
            if ! [[ "${RAW,,}" =~ ^(0x[0-9a-f]+|[0-9]+)$ ]]; then
                report_error "mlxconfig SET readback returned non-numeric value for ${PARAM}: ${RAW}"
                RC=1
                continue
            fi
            if [[ "${RAW,,}" == 0x* ]]; then
                HEX="${RAW:2}"
                HEX="${HEX#"${HEX%%[!0]*}"}"
                if (( ${#HEX} > 2 )); then
                    report_error "mlxconfig SET readback port out of range for ${PARAM}: ${RAW}"
                    RC=1
                    continue
                fi
                RAW_NUM=$((16#${HEX:-0}))
            elif normalize_uint "$RAW" "$ALL_PORTS_ID"; then
                RAW_NUM="$NORMALIZED_UINT"
            else
                report_error "mlxconfig SET readback port out of range for ${PARAM}: ${RAW}"
                RC=1
                continue
            fi
            if (( RAW_NUM != RAW_EXPECTED )); then
                report_error "mlxconfig SET readback mismatch for ${PARAM}: expected ${RAW_EXPECTED}, next-boot ${RAW}"
                RC=1
                continue
            fi
            VERIFIED[$i]=1
            continue
        fi

        EXPECTED_YANG="${REV[$PARAM:$RAW_EXPECTED]:-$VALUE}"
        ACTUAL="${REV[$PARAM:$RAW]:-$RAW}"
        [[ -n "${DMS_BACKEND_TRACE:-}" ]] && \
            echo "mlxconfig-wrapper: verify ${PARAM} requested=${VALUE} expected=${EXPECTED_YANG} raw_expected=${RAW_EXPECTED} next_boot=${ACTUAL} raw=${RAW}" >&2
        trace "SET-VERIFY param=${PARAM} requested=${VALUE} expected=${EXPECTED_YANG} raw_expected=${RAW_EXPECTED} next_boot=${ACTUAL} raw=${RAW}"
        if [[ "$ACTUAL" != "$EXPECTED_YANG" ]]; then
            report_error "mlxconfig SET readback mismatch for ${PARAM}: requested ${VALUE} (normalized ${EXPECTED_YANG}, raw ${RAW_EXPECTED}), next-boot ${ACTUAL} (raw ${RAW})"
            RC=1
            continue
        fi
        VERIFIED[$i]=1
        if [[ "$OP" == "SET" ]]; then
            echo "${LEAF_NAME}=${VALUE}"
        fi
    done
    # A lanes request succeeds only when all of its expanded parameters verify.
    REPORT=""
    for REQUEST in "${!REQUEST_INDICES[@]}"; do
        REQUEST_OK=1
        for INDEX in ${REQUEST_INDICES[$REQUEST]}; do
            [[ "${VERIFIED[$INDEX]}" == 1 ]] || REQUEST_OK=0
        done
        if [[ "$OP" == "SET-BATCH" ]]; then
            REPORT+="$REQUEST_OK"
        elif [[ "$REQUEST_OK" == 1 && -n "${REQUEST_LANES[$REQUEST]}" ]]; then
            echo "lanes=${REQUEST_LANES[$REQUEST]}"
        fi
    done
    if [[ "$OP" == "SET-BATCH" ]]; then
        printf 'DMS_SET_RESULTS=%s\n' "$REPORT"
    fi
    exit $RC
fi
