#! /bin/sh
set -e

# Regression test for HIP GPU autodetection via find_package(hip).
#
# When an application does not set GPU_TARGETS, hip-config-amd.cmake runs
# amdgpu-arch to detect the installed GPUs. On the Debian/Ubuntu layout
# amdgpu-arch lives in the versioned LLVM bindir (/usr/lib/llvm-N/bin),
# not under ${ROCM_PATH}/llvm or ${ROCM_PATH}/bin. If HIP_CLANG_ROOT is
# wrong, detection silently fails, GPU_TARGETS stays empty and device code
# falls back to gfx906, segfaulting at runtime (see d/p/0026).
#
# This test asserts that cmake's autodetected GPU_BUILD_TARGETS matches what
# amdgpu-arch reports directly. It needs a real GPU, so it skips (exit 77)
# when none is present.

# Use the clang/amdgpu-arch that matches the installed HIP toolchain.
ROCM_CLANG_PREFIX=$(hipcc --version 2>/dev/null | sed -n 's/^InstalledDir:[[:space:]]*//p')
ROCM_CLANG_PREFIX="${ROCM_CLANG_PREFIX:-/usr/bin}"

if [ "${AUTOPKGTEST_TMP}" = "" ]
then
	AUTOPKGTEST_TMP=$(mktemp -d /tmp/${pkg}-test.XXXXXX)
	# shellcheck disable=SC2064
	trap "rm -rf ${AUTOPKGTEST_TMP}" 0 INT QUIT ABRT PIPE TERM
fi
cd "$AUTOPKGTEST_TMP"

ARCH=$("${ROCM_CLANG_PREFIX}/amdgpu-arch" 2>/dev/null | grep -v '^gfx000$' | head -n1 || true)
if [ -z "$ARCH" ]; then
	echo "no AMD GPU detected by amdgpu-arch; skipping autodetection test"
	exit 77
fi
echo "amdgpu-arch reports: $ARCH"

cat > main.cpp << END
#include <hip/hip_runtime.h>
int main() { return 0; }
END

cat > CMakeLists.txt << END
cmake_minimum_required(VERSION 3.22)
project(example LANGUAGES CXX)
find_package(hip REQUIRED)
add_executable(ex main.cpp)
target_link_libraries(ex PRIVATE hip::device)
END

echo '$ cat CMakeLists.txt'
cat CMakeLists.txt
echo "$ CXX=${ROCM_CLANG_PREFIX}/clang++ cmake -S. -Bbuild"
CXX=${ROCM_CLANG_PREFIX}/clang++ cmake -S. -Bbuild

GPU_BUILD_TARGETS=$(sed -n 's/^GPU_BUILD_TARGETS:STRING=//p' build/CMakeCache.txt)
echo "cmake autodetected GPU_BUILD_TARGETS: '${GPU_BUILD_TARGETS}'"

case ";${GPU_BUILD_TARGETS};" in
	*";${ARCH};"*)
		echo "PASS: GPU autodetection matches amdgpu-arch"
		;;
	*)
		echo "FAIL: GPU autodetection did not pick up ${ARCH};" \
		     "HIP_CLANG_ROOT/amdgpu-arch lookup is broken"
		exit 1
		;;
esac
