#!/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"); VALUE="$2"

# YANG-enum int -> PAOS admin_status decode.
#
# YANG admin-state enum: up=1, down=2 (matches PAOS register field exactly).
# libdms converts the YANG name to the YANG int before dispatch, so by the
# time we get here $VALUE is "1" or "2", not "up" or "down". The previous
# code did `[[ "$VALUE" == "up" ]] && V=1 || V=2` which fell through to V=2
# for every libdms-dispatched SET (even when the operator wrote "up"),
# silently flipping admin=up requests into admin=down writes.
#
# Accept both forms (int from libdms, string from direct CLI / tests).
declare -A YANG_ENUM=(
    ["admin-status:1"]="1"
    ["admin-status:2"]="2"
    ["admin-status:up"]="1"
    ["admin-status:down"]="2"
)
V="${YANG_ENUM[admin-status:$VALUE]:-}"
if [[ -z "$V" ]]; then
    echo "Error: mlxreg-port-admin-set: bad admin-status value '$VALUE' (expected up/down/1/2)" >&2
    exit 1
fi

ERR_FILE=$(mktemp /tmp/dms-mlxreg-port-admin-set.XXXXXX) || exit 1
trap 'rm -f "$ERR_FILE"' EXIT

if ! mlxreg -d "$BDF" -y --set "admin_status=${V},fd=1,ase=1" --reg_name PAOS --indexes 'local_port=1,lp_msb=0' 2>"$ERR_FILE"; then
    ERR=$(cat "$ERR_FILE" 2>/dev/null)
    echo "Error: mlxreg PAOS SET failed: ${ERR:-unknown}" >&2
    exit 1
fi

# Echo back the canonical YANG name so dms-tool sees a consistent string,
# regardless of whether the caller sent "up", "1", "down", or "2". $V is
# always "1" or "2" at this point (validated by YANG_ENUM lookup above).
declare -A NAME_OF=(
    ["1"]="up"
    ["2"]="down"
)
echo "admin-status=${NAME_OF[$V]}"
