#!/bin/sh
# Build a gtest filter from debian/tests/flaky-tests.list and run the hipfft
# accuracy suite. The same pattern list drives both autopkgtest groups:
#
#   run-test-group main    run everything EXCEPT the flaky patterns  (gating)
#   run-test-group flaky   run ONLY the flaky patterns  (Restrictions: flaky)
#
# Keeping the (long) list in flaky-tests.list keeps debian/tests/control
# readable: one pattern per line instead of one giant colon-joined string.
set -eu

group="${1:-}"
here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
list="$here/flaky-tests.list"

if [ ! -f "$list" ]; then
    echo "$0: pattern list not found: $list" >&2
    exit 1
fi

# Drop comments and blank lines, trim surrounding whitespace, join with ':'.
patterns=$(sed -e 's/#.*$//' -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' \
                 "$list" | grep -v '^$' | paste -sd: -)

if [ -z "$patterns" ]; then
    echo "$0: no patterns parsed from $list" >&2
    exit 1
fi

case "$group" in
    main)  filter="*-$patterns" ;;   # negation: all colon-separated pats negative
    flaky) filter="$patterns" ;;     # positive: only the listed pats
    *)
        echo "usage: $0 <main|flaky>" >&2
        exit 2
        ;;
esac

# hipfft-test's --V budgets tests against TOTAL device memory by default, so
# on a shared CI GPU where other autopkgtests already hold VRAM, large tests
# can pass the pre-flight fit check and then fail with spurious accuracy
# errors instead of being skipped. Pass the currently FREE VRAM (min across
# devices) instead, when rocm-smi is available.
free_gib=$(rocm-smi --showmeminfo vram --csv 2>/dev/null | awk -F',' '
    NR==1 {
        for (i=1; i<=NF; i++) {
            if ($i == "VRAM Total Memory (B)") t=i
            if ($i == "VRAM Total Used Memory (B)") u=i
        }
        next
    }
    t && u {
        free = $t - $u
        if (min == "" || free < min) min = free
    }
    END { if (min != "") print int(min / 1073741824) }
') || free_gib=

vopt=
[ -n "$free_gib" ] && vopt="--V=$free_gib"

exec rocm-test-launcher /usr/libexec/rocm/libhipfft0-tests/run-tests \
    --gtest_filter="$filter" $vopt
