#!/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: PIPG register capability query
# Tries mlxreg PIPG → syndrome = register unsupported (all false)
#                    → success = read cap fields (ipg_min_cap, ipg_max_cap, ipg_res_cap)
# oper-supported: inferred from register accessibility
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; }

OUTPUT=$(mlxreg -d "$BDF" --get --reg_name PIPG --indexes "local_port=1,lp_msb=0,ipg_cap_index=0" 2>&1)

if echo "$OUTPUT" | grep -qi "syndrome\|error\|failed"; then
    for PARAM in "$@"; do
        case "$PARAM" in
            ipg_supported)      echo "supported=false" ;;
            ipg_oper_supported) echo "oper-supported=false" ;;
            ipg_min_cap)        echo "min=0" ;;
            ipg_max_cap)        echo "max=0" ;;
            ipg_res_cap)        echo "resolution=0" ;;
            *)                  echo "${PARAM}=0" ;;
        esac
    done
    exit 0
fi

for PARAM in "$@"; do
    case "$PARAM" in
        ipg_supported)
            echo "supported=true" ;;
        ipg_oper_supported)
            echo "oper-supported=true" ;;
        ipg_min_cap)
            VAL=$(echo "$OUTPUT" | grep -E "^\s*ipg_min_cap\s" | awk '{print $NF}' | sed 's/0x//')
            [[ -n "$VAL" ]] && VAL=$((16#${VAL})) || VAL=0
            echo "min=${VAL}" ;;
        ipg_max_cap)
            VAL=$(echo "$OUTPUT" | grep -E "^\s*ipg_max_cap\s" | awk '{print $NF}' | sed 's/0x//')
            [[ -n "$VAL" ]] && VAL=$((16#${VAL})) || VAL=0
            echo "max=${VAL}" ;;
        ipg_res_cap)
            VAL=$(echo "$OUTPUT" | grep -E "^\s*ipg_res_cap\s" | awk '{print $NF}' | sed 's/0x//')
            [[ -n "$VAL" ]] && VAL=$((16#${VAL})) || VAL=0
            echo "resolution=${VAL}" ;;
        *)
            echo "${PARAM}=0" ;;
    esac
done
