#!/bin/sh
set -e

DATADIR=/usr/share/pkg-rocm-tools/data/build-targets
TARGET_FILE="$DATADIR/unstable"

# Determine expected output based on distro
if [ -f /etc/os-release ]; then
	. /etc/os-release
	if [ "${NAME:-}" = "Ubuntu" ]; then
		TARGET_FILE="$DATADIR/ubuntu-devel"
		echo "Detected Ubuntu - expecting ubuntu-devel targets"
	fi
fi

# Read expected targets from file (skip comments and blank lines, join with spaces)
# This could be overthinking regarding allowing comments in target lists
EXPECTED=$(grep -v '^#' "$TARGET_FILE" | grep -v '^$' | tr '\n' ' ' | sed 's/ $//')

# rocm-target-arch requires debian/changelog, so create a temp environment
WORKDIR=$(mktemp -d)
trap 'rm -rf "$WORKDIR"' EXIT

mkdir "$WORKDIR/debian"
echo "test (1.0) unstable; urgency=low" >"$WORKDIR/debian/changelog"

cd "$WORKDIR"
echo "Running rocm-target-arch:"
OUTPUT=$(rocm-target-arch)
echo "$OUTPUT"

echo ""
echo "Validating output..."
if [ "$OUTPUT" = "$EXPECTED" ]; then
	echo "PASS: Output matches expected targets"
else
	echo "FAIL: Output does not match"
	echo "Expected: $EXPECTED"
	echo "Got:      $OUTPUT"
	exit 1
fi
