#!/bin/sh
set -e

# stderr messages that are safe to tolerate: they only indicate a capability
# the running kernel doesn't support yet (e.g. a feature newer than the
# testbed kernel), not an actual defect in rocminfo. Add new tolerated
# messages here, one per line, rather than silencing all stderr output.
tolerated=$(mktemp)
captured=$(mktemp)
trap 'rm -f "$tolerated" "$captured"' EXIT
cat > "$tolerated" <<'EOF'
Secondary CUID not available: AMDCUID support not enabled.
EOF

if [ -d /sys/class/kfd ]; then
  echo 'Running rocminfo and expecting GPU information'
  rocminfo 2>"$captured"
else
  echo 'Running rocminfo and expecting no GPU found'
  rocminfo 2>"$captured" | sed '/ROCk module is NOT/,$b;$q1'
fi

if [ -s "$captured" ]; then
  unexpected=$(grep -Fvxf "$tolerated" "$captured" || true)
  if [ -n "$unexpected" ]; then
    echo "$unexpected" >&2
    echo 'Unexpected stderr output from rocminfo (see above) -- treating as failure.' >&2
    exit 1
  fi
  echo '#####################################################################'
  echo '## WARNING: rocminfo emitted tolerated warning(s) on stderr.'
  echo '## This test still PASSES, but the warning below likely means the'
  echo '## testbed kernel is outdated relative to this rocminfo version.'
  echo '#####################################################################'
  cat "$captured"
  echo '#####################################################################'
fi
