#!/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
#
# Real: ROCE_ACCL register _field_select bit capability query
# Tries mlxreg ROCE_ACCL → syndrome = register unsupported (all false)
#                         → success = parse _field_select bits per leaf
source "$(dirname "$0")/_lib.sh"
trace "$@"

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

[[ "$OP" != "GET" ]] && { echo "Error: caps are read-only" >&2; exit 1; }

declare -A PARAM_TO_LEAF=(
    ["roce_adp_retrans_field_select"]="adaptive-retransmission"
    ["roce_tx_window_field_select"]="tx-window"
    ["roce_slow_restart_field_select"]="slow-restart"
    ["roce_slow_restart_idle_field_select"]="slow-restart-idle"
    ["adaptive_routing_forced_en_field_select"]="adaptive-routing-force"
    ["selective_repeat_forced_en_field_select"]="selective-repeat"
    ["cc_per_plane_en_field_select"]="cc-per-plane"
)

unsupported_roce_accl() {
    echo "$1" | grep -Eqi "syndrome.*(not supported|unsupported)|register.*(not supported|unsupported)|not supported|unsupported"
}

if ! OUTPUT=$(mlxreg -d "$BDF" --get --reg_name ROCE_ACCL 2>&1); then
    if unsupported_roce_accl "$OUTPUT"; then
        for PARAM in "$@"; do
            LEAF="${PARAM_TO_LEAF[$PARAM]:-$PARAM}"
            echo "${LEAF}=false"
        done
        exit 0
    fi
    echo "Error: mlxreg ROCE_ACCL query failed for $BDF: $OUTPUT" >&2
    exit 1
fi

if echo "$OUTPUT" | grep -Eqi "permission denied|operation not permitted|failed|error"; then
    if unsupported_roce_accl "$OUTPUT"; then
        for PARAM in "$@"; do
            LEAF="${PARAM_TO_LEAF[$PARAM]:-$PARAM}"
            echo "${LEAF}=false"
        done
        exit 0
    fi
    echo "Error: mlxreg ROCE_ACCL query returned an error for $BDF: $OUTPUT" >&2
    exit 1
fi

if unsupported_roce_accl "$OUTPUT"; then
    for PARAM in "$@"; do
        LEAF="${PARAM_TO_LEAF[$PARAM]:-$PARAM}"
        echo "${LEAF}=false"
    done
    exit 0
fi

for PARAM in "$@"; do
    LEAF="${PARAM_TO_LEAF[$PARAM]:-$PARAM}"
    # Extract the field_select value: look for exact param name
    VAL=$(echo "$OUTPUT" | grep -E "^\s*${PARAM}\s" | awk '{print $NF}')
    if [[ "$VAL" == "0x00000001" ]]; then
        echo "${LEAF}=true"
    else
        echo "${LEAF}=false"
    fi
done
