#!/bin/bash
# Stock diag/Mellanox/<PSID>/lts with fleet NIC firmware, pulled straight
# from the vendor sources (downloads.dell.com / content.mellanox.com).
#
# Run from the mirror docroot (the directory that contains diag/):
#   bash stock-mellanox-firmware.sh
#
# Layout matches the existing entries (e.g. diag/Mellanox/MT_0000000531/):
# the versioned zip (containing exactly one flint-burnable .bin for that
# PSID) sits under its real name, and "lts" is a symlink pointing at it.
#
# Stock-NVIDIA cards (MT_*) have direct PSID-specific downloads on
# content.mellanox.com (already zips - shipped as-is). Dell OEM cards (DEL*)
# are only distributed inside Dell Update Packages: modern DUPs are also
# valid zip archives with the bins under payload/; older ones (the CX4-Lx
# era) are shell self-extractors with an embedded tar.gz, so those are
# carved out via the DUP's own "#####Startofarchive#####" marker.
#
# One DUP carries bins for SEVERAL PSIDs (one per board model, same release),
# so each bin is re-zipped alone under its own PSID path. When mstflint or
# flint is installed, every image's embedded PSID is verified against the
# path it's stocked under before placement.
#
# Version policy (per Helius "latest" request, 2026-09): DEL* pins track the
# newest Dell DUP for each card family, MT_* additions track the newest
# vendor release for that card. NOTE: this can run ahead of the DSU "stable"
# snapshot (diag/Dell/stable) - harmless, since on Dell chassis DSU owns the
# card and the MAAS script only applies this tree on non-Dell chassis.
set -euo pipefail

DEST="diag/Mellanox"
[ -d "$DEST" ] || { echo "run this from the mirror docroot ($DEST/ not found here)"; exit 1; }

WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT

FLINT=""
command -v flint >/dev/null 2>&1 && FLINT=flint
command -v mstflint >/dev/null 2>&1 && FLINT=mstflint
[ -n "$FLINT" ] || echo "NOTE: mstflint/flint not installed - stocking WITHOUT PSID verification"

verify_psid() { # <expected psid> <bin file>
  [ -n "$FLINT" ] || return 0
  local got
  got=$("$FLINT" -i "$2" query 2>/dev/null | awk '/^PSID:/{print $2}')
  if [ "$got" != "$1" ]; then
    echo "FATAL: image PSID '$got' != expected '$1' for $(basename "$2") - wrong bin mapping, nothing stocked"
    exit 1
  fi
}

# Mirror convention: the versioned zip lives under its real name and "lts"
# is a symlink to it, so `ls` shows what's pinned (matches the pre-existing
# entries, e.g. MT_0000000531).
place() { # <psid> <source file> <versioned zip name>
  mkdir -p "$DEST/$1"
  cp "$2" "$DEST/$1/$3"
  ln -sfn "$3" "$DEST/$1/lts"
  echo "stocked: $DEST/$1/lts -> $3  ($(du -h "$DEST/$1/$3" | cut -f1))"
}

# re-zip one bin alone and place it: <psid> <dir containing bin> <bin name>
zip_and_place() {
  verify_psid "$1" "$2/$3"
  rm -f "$WORK/one.zip"
  (cd "$2" && zip -q "$WORK/one.zip" "$3")
  place "$1" "$WORK/one.zip" "$3.zip"
}

########################################################################
# Stock NVIDIA cards - direct downloads (already-zipped, ship as-is)
########################################################################

NVIDIA_BASE="https://content.mellanox.com/firmware"

stock_nvidia() { # <psid> <zip filename>
  curl -fsSL "$NVIDIA_BASE/$2" -o "$WORK/$2"
  if [ -n "$FLINT" ]; then
    rm -rf "$WORK/v" && mkdir "$WORK/v"
    unzip -o -q "$WORK/$2" -d "$WORK/v"
    verify_psid "$1" "$(find "$WORK/v" -name '*.bin' | head -n 1)"
  fi
  place "$1" "$WORK/$2" "$2"
}

# ConnectX-6 Dx, FW 22.42.1000
stock_nvidia MT_0000000437 "fw-ConnectX6Dx-rel-22_42_1000-MCX623106AS-CDA_Ax-UEFI-14.35.15-FlexBoot-3.7.500.signed.bin.zip"
stock_nvidia MT_0000000773 "fw-ConnectX6Dx-rel-22_42_1000-MCX623436MS-CDA_Ax-UEFI-14.35.15-FlexBoot-3.7.500.signed.bin.zip"

# ConnectX-6 Dx (MCX623106AN-CDA/CDAT), FW 22.50.1002 - Helius SVC-23496
stock_nvidia MT_0000000359 "fw-ConnectX6Dx-rel-22_50_1002-MCX623106AN-CDA_Ax-UEFI-14.43.10-FlexBoot-3.9.101.bin.zip"

# ConnectX-5 Ex (MCX516A-CDA/CDAT), FW 16.35.8008 (2022 LTS U8 - the CX5
# line's maintained branch; plain-GA 16.35.1012 is older) - Helius SVC-10774,
# SVC-11330
stock_nvidia MT_0000000013 "fw-ConnectX5-rel-16_35_8008-MCX516A-CDA_Ax_Bx-UEFI-14.29.15-FlexBoot-3.6.902.bin.zip"

# DEL0000000005 is Dell OEM (CX5 Ex, Dell parts 0VC496/06FKDT) but NVIDIA
# hosts direct zips for it - no DUP extraction needed. 16.32.2004 is that
# card's final release (EOL). Candidate PSID for the older Helius CX5 Ex
# boxes (the newer Dell CX5 Ex part 09FTMY/071C1T is DEL0000000004 below).
stock_nvidia DEL0000000005 "fw-ConnectX5-rel-16_32_2004-0VC496_06FKDT_Ax-FlexBoot-3.6.502.bin.zip"

########################################################################
# Dell OEM cards - extract PSID-matched .bin from the official Dell DUP
########################################################################

extract_dup() { # <dup url> <psid>:<payload bin name> ...
  local url=$1; shift
  local dup
  dup="$WORK/$(basename "$url")"
  echo "downloading DUP: $url"
  curl -fsSL "$url" -o "$dup"
  local spec psid bin
  for spec in "$@"; do
    psid=${spec%%:*}
    bin=${spec#*:}
    unzip -o -q -j "$dup" "payload/$bin" -d "$WORK"
    zip_and_place "$psid" "$WORK" "$bin"
    rm -f "$WORK/$bin"
  done
}

# Old-format DUP (shell self-extractor with embedded tar.gz), same payload/
# layout inside. Carved out with the DUP's own archive marker.
extract_old_dup() { # <dup url> <psid>:<payload bin name> ...
  local url=$1; shift
  local dup
  dup="$WORK/$(basename "$url")"
  echo "downloading DUP (old format): $url"
  curl -fsSL "$url" -o "$dup"
  local mark out="$WORK/olddup"
  mark=$(LC_ALL=C grep -m2 -an '#####Startofarchive#####' "$dup" | tail -n1 | cut -d: -f1)
  [ -n "$mark" ] || { echo "FATAL: archive marker not found in $(basename "$dup")"; exit 1; }
  rm -rf "$out" && mkdir "$out"
  # the embedded tar has one cosmetic unnamed entry; tolerate tar's complaint
  # and check for the actual files instead
  tail -n +$((mark + 1)) "$dup" | tar xzf - -C "$out" payload 2>/dev/null || true
  local spec psid bin
  for spec in "$@"; do
    psid=${spec%%:*}
    bin=${spec#*:}
    [ -f "$out/payload/$bin" ] || { echo "FATAL: $bin not found in $(basename "$dup") payload"; exit 1; }
    zip_and_place "$psid" "$out/payload" "$bin"
  done
}

# ConnectX-6 LX, FW 26.44.10.36 (Dell R6615/R7615 etc.)
extract_dup "https://downloads.dell.com/FOLDER13035714M/2/Network_Firmware_K65HP_LN_26.44.10.36_A00_01.BIN" \
  "DEL0000000030:fw-ConnectX6Lx-rel-26_44_1036-0DN78C_Ax-UEFI-14.37.14-FlexBoot-3.7.500.signed.bin" \
  "DEL0000000031:fw-ConnectX6Lx-rel-26_44_1036-06XJXK_0R5WK9_Ax-UEFI-14.37.14-FlexBoot-3.7.500.signed.bin"

# ConnectX-6 DX, FW 22.48.10.00 (Dell R6515 etc.; also Helius SVC-6839,
# SVC-19629, SVC-20559)
extract_dup "https://downloads.dell.com/FOLDER14351253M/1/Network_Firmware_81T4K_LN_22.48.10.00_A00.BIN" \
  "DEL0000000027:fw-ConnectX6Dx-rel-22_48_1000-0F6FXM_08P2T2_Ax-UEFI-14.41.14-FlexBoot-3.9.101.signed.bin" \
  "DEL0000000046:fw-ConnectX6Dx-rel-22_48_1000-0FD63G_Ax-UEFI-14.41.14-FlexBoot-3.9.101.signed.bin"

# ConnectX-5 family, FW 16.35.80.02 (Dell R6515 etc.). DEL0000000004 is the
# newer Dell CX5 Ex 100G part (09FTMY/071C1T - per this DUP's configfile.xml,
# PCI device 1019 = CX5 Ex); candidate for the Helius CX5 Ex boxes.
extract_dup "https://downloads.dell.com/FOLDER14280296M/1/Network_Firmware_P5F14_LN_16.35.80.02_A00.BIN" \
  "DEL0000000004:fw-ConnectX5-rel-16_35_8002-09FTMY_071C1T_Ax-UEFI-14.29.15-FlexBoot-3.6.902.signed.bin" \
  "DEL0000000015:fw-ConnectX5-rel-16_35_8002-0V5DG9_0TDNNT_Ax-UEFI-14.29.15-FlexBoot-3.6.902.signed.bin" \
  "DEL0000000016:fw-ConnectX5-rel-16_35_8002-04TRD3_Ax-UEFI-14.29.15-FlexBoot-3.6.902.signed.bin"

# ConnectX-4 Lx, FW 14.25.80.00 (Dell OEM cards found in Supermicros: 66B,
# 92H, 20D, X10DRi fleet)
extract_old_dup "https://downloads.dell.com/FOLDER05946734M/3/Network_Firmware_5T22D_LN_14.25.80.00_02.BIN" \
  "DEL2420110034:fw-ConnectX4Lx-rel-14_25_8000-020NJD_0MRT0D_Ax-UEFI-14.18.22-FlexBoot-3.5.702.bin" \
  "DEL0000000002:fw-ConnectX4Lx-rel-14_25_8000-0WCHFY_Ax-UEFI-14.18.22-FlexBoot-3.5.702.signed.bin" \
  "DEL2810000034:fw-ConnectX4Lx-rel-14_25_8000-0R887V-UEFI-14.18.22-FlexBoot-3.5.702.bin"

echo ""
echo "done - 15 PSIDs stocked under $DEST/"
