#!/bin/sh -e

# Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
#    list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and documentation are those
# of the authors and should not be interpreted as representing official policies,
# either expressed or implied, of the FreeBSD Project.

PROGNAME=bfvcheck

err () {
    echo "$PROGNAME: $*" >&2
}

# Set BFVCHECK_VERBOSE=1 to print data sources and timings to stderr.
vlog () {
    [ -n "$BFVCHECK_VERBOSE" ] || return 0
    echo "$PROGNAME: [$(cut -d' ' -f1 /proc/uptime)s] $*" >&2
}

# Normalize "32.51.344" / "32.51.0344" to "32.51.0344"; pass anything else through.
norm_ver () {
    echo "$1" | awk -F. 'NF==3 && $1 ~ /^[0-9]+$/ && $2 ~ /^[0-9]+$/ && $3 ~ /^[0-9]+$/ \
        { printf "%d.%d.%04d\n", $1, $2, $3; next } { print }'
}

bf_chip=$(bffamily --chip)


echo "Beginning version check..."
vlog "start"

# bfb file used to extract ATF/UEFI's expected version information
BOOTIMG_LOCATION=/lib/firmware/mellanox/boot/default.bfb

# If set to anything, the script will exit with an exit code of 1.
version_error=
FW_UPDATED=no

# Compares two version strings, and prints a big red error if they aren't equal.
# $1 and $2 - the version strings to compare
# $3 - the name of the software we're testing the version of
compare_versions () {
    if [ "$1" != "$2" ]; then
        printf "\033[0;31mWARNING: %s VERSION DOES NOT MATCH RECOMMENDED!\033[0m\n" "$3"
        version_error=ERR
        echo ""
    fi
}

bfver_out="$( bfver --file $BOOTIMG_LOCATION )"
BUILD_ATF=$( echo "$bfver_out" | grep -m 1 "ATF" | cut -d':' -f 2,3 | \
    sed -e 's/[[:space:]]//' )
BUILD_UEFI=$( echo "$bfver_out" | grep -m 1 "UEFI" | cut -d':' -f 2 | \
    sed -e 's/[[:space:]]//' )

bfver_out="$( bfver )"
RUNTIME_ATF=$( echo "$bfver_out" | grep -m 1 "ATF" | cut -d':' -f 2,3 | \
    sed -e 's/[[:space:]]//' )
RUNTIME_UEFI=$( echo "$bfver_out" | grep -m 1 "UEFI" | cut -d':' -f 2 | \
    sed -e 's/[[:space:]]//' )
vlog "bfver done"

#
# Installed FW version and PSID, read from the mlx5 driver through devlink
# (ethtool -i as fallback). The driver uses its own firmware command queue,
# so this does not contend for the NIC's ICMD interface with MFT tools.
#
PCIDEV=$(lspci -nD 2> /dev/null | grep 15b3:a2d[26c] | awk '{print $1}' | head -1)
PSID=
RUNTIME_FW=
STORED_FW=
FW_SOURCE=

if [ -z "$PCIDEV" ]; then
    err "Could not find the ConnectX PCI device."
elif command -v devlink > /dev/null 2>&1; then
    dl_out=$(devlink dev info "pci/$PCIDEV" 2>&1)
    dl_rc=$?
    if [ $dl_rc -eq 0 ]; then
        # devlink dev info layout:
        #   versions:
        #       fixed:   fw.psid MT_...
        #       running: fw.version 32.51.0344
        #       stored:  fw.version 32.51.0344
        PSID=$(echo "$dl_out" | awk '$1 == "fw.psid" { print $2; exit }')
        RUNTIME_FW=$(echo "$dl_out" | awk '
            /^[[:space:]]*fixed:/   { s = "f" }
            /^[[:space:]]*running:/ { s = "r" }
            /^[[:space:]]*stored:/  { s = "s" }
            s == "r" && $1 == "fw.version" { print $2; exit }')
        STORED_FW=$(echo "$dl_out" | awk '
            /^[[:space:]]*fixed:/   { s = "f" }
            /^[[:space:]]*running:/ { s = "r" }
            /^[[:space:]]*stored:/  { s = "s" }
            s == "s" && $1 == "fw.version" { print $2; exit }')
        FW_SOURCE="devlink pci/$PCIDEV"
    else
        vlog "devlink dev info pci/$PCIDEV failed (rc=$dl_rc): $dl_out"
    fi
else
    vlog "devlink command not found"
fi

# Fallback: ethtool -i on a netdev of the PF ("32.51.0344 (MT_0000000884)").
# Gives the running version and PSID only, so no reset-pending detection.
if [ -n "$PCIDEV" ] && { [ -z "$RUNTIME_FW" ] || [ -z "$PSID" ]; }; then
    for nd in $(ls /sys/bus/pci/devices/"$PCIDEV"/net 2> /dev/null); do
        fwv=$(ethtool -i "$nd" 2> /dev/null | sed -n 's/^firmware-version:[[:space:]]*//p')
        [ -n "$fwv" ] || continue
        [ -n "$RUNTIME_FW" ] || RUNTIME_FW=${fwv%% *}
        [ -n "$PSID" ] || PSID=$(echo "$fwv" | sed -n 's/.*(\([^)]*\)).*/\1/p')
        FW_SOURCE="${FW_SOURCE:+$FW_SOURCE + }ethtool $nd"
        break
    done
fi

RUNTIME_FW=$(norm_ver "$RUNTIME_FW")
STORED_FW=$(norm_ver "$STORED_FW")

# The driver reports stored == running when no image is pending.
[ -n "$STORED_FW" ] || STORED_FW=$RUNTIME_FW
LOADED_FW=$STORED_FW
if [ -n "$RUNTIME_FW" ] && [ "$STORED_FW" != "$RUNTIME_FW" ]; then
    FW_UPDATED=yes
fi

if [ -z "$RUNTIME_FW" ]; then
    err "Could not read the installed firmware version from the driver (devlink/ethtool)."
fi
vlog "installed FW=${RUNTIME_FW:-?} stored=${STORED_FW:-?} PSID=${PSID:-?} source=${FW_SOURCE:-none}"

#
# Recommended FW from the bundled firmware package. "--list" only reads the
# package; it does not access the device. The result is cached per package
# and PSID so the package is not unpacked on every run.
#
BUILD_FW=
bfhcafw_status=0
mlxfw=$(bfhcafw find) || bfhcafw_status=$?

if [ "$bfhcafw_status" -ne 0 ]; then
    # FW package not found anywhere, so error out fw check
    # We keep going to check bootloader versions anyway.
    err "The firmware package could not be located."
    err "Firmware check will fail."
    BUILD_FW=ERROR
elif [ -z "$PSID" ]; then
    err "Board PSID unknown; cannot look up the recommended firmware version."
    BUILD_FW=ERROR
else
    CACHE=/var/cache/bfvcheck/recommended
    cache_key="$mlxfw $(stat -c '%s %Y' "$mlxfw" 2> /dev/null) $PSID"

    if [ -r "$CACHE" ] && [ "$(sed -n 1p "$CACHE")" = "$cache_key" ]; then
        BUILD_FW=$(sed -n 2p "$CACHE")
        vlog "recommended FW from cache $CACHE"
    else
        vlog "running $mlxfw --list"
        list_out=$("$mlxfw" --list 2>&1)
        list_rc=$?
        vlog "--list done (rc=$list_rc)"
        if [ $list_rc -ne 0 ]; then
            err "There was an error reading the firmware package (rc=$list_rc):"
            echo "$list_out" | tail -5 >&2
            BUILD_FW=ERROR
        else
            # Rows: PN  PSID  Version  Tag  Description. Take the first
            # x.y.z token after the PSID rather than a fixed column.
            BUILD_FW=$(echo "$list_out" | awk -v p="$PSID" '
                { for (i = 1; i <= NF; i++) if ($i == p) {
                      for (j = i + 1; j <= NF; j++)
                          if ($j ~ /^[0-9]+\.[0-9]+\.[0-9]+$/) { print $j; exit }
                  } }')
            BUILD_FW=$(norm_ver "$BUILD_FW")
            # PSID not in the package: handled by the N/A branch below.
            [ -n "$BUILD_FW" ] || BUILD_FW="N/A"
            if mkdir -p "$(dirname "$CACHE")" 2> /dev/null; then
                printf '%s\n%s\n' "$cache_key" "$BUILD_FW" > "$CACHE" 2> /dev/null
            fi
        fi
    fi
fi
vlog "recommended FW=$BUILD_FW"

echo ""

cat << EOF
-RECOMMENDED VERSIONS-
ATF: $BUILD_ATF
UEFI: $BUILD_UEFI
FW: $BUILD_FW
EOF

cat << EOF

-INSTALLED VERSIONS-
ATF: $RUNTIME_ATF
UEFI: $RUNTIME_UEFI
FW: $RUNTIME_FW

EOF

compare_versions "$BUILD_ATF" "$RUNTIME_ATF" "ATF"
compare_versions "$BUILD_UEFI" "$RUNTIME_UEFI" "UEFI"

if [ "$BUILD_FW" = "N/A" ]; then
    BOARD_PN="$(lspci -s $(bfhcafw bus) -vv | grep '\[PN\]' | cut -d' ' -f4-)"
    cat << EOF
WARNING: The bundled firmware manager does not include firmware for
this board. Recommended firmware version cannot be determined.

Firmware Manager Path: $mlxfw
Part Number: $BOARD_PN

EOF
    version_error=ERR
else
    compare_versions "$BUILD_FW" "$RUNTIME_FW" "FW"
fi

if [ "$FW_UPDATED" = "yes" ]; then
    cat << EOF
WARNING: The firmware has been updated to $LOADED_FW, but the chassis
must be power cycled for changes to take effect.

EOF
fi

echo "Version check complete."
vlog "end"

if [ -z "$version_error" ] && [ $FW_UPDATED = "no" ]; then
    echo "No issues found."
    exit 0
fi

exit 1
