#!/bin/sh

# This script has to be run with the working directory being "test"
# This runs the tests on the libkrun instance found by pkg-config.
# Specify PKG_CONFIG_PATH env variable to test a non-system installation of libkurn.

set -e

OS=$(uname -s)
 # macOS uses the string "arm64" but Rust uses "aarch64"
ARCH=$(uname -m | sed 's/^arm64$/aarch64/')

# Set the OS-specific library path from LIBKRUN_LIB_PATH.
# On macOS, SIP strips DYLD_LIBRARY_PATH when executing scripts via a shebang,
# so the Makefile passes it through this alternative variable instead.
# We do the same on Linux for consistency.
if [ -n "${LIBKRUN_LIB_PATH}" ]; then
	if [ "$OS" = "Darwin" ]; then
		export DYLD_LIBRARY_PATH="${LIBKRUN_LIB_PATH}:${DYLD_LIBRARY_PATH}"
	else
		export LD_LIBRARY_PATH="${LIBKRUN_LIB_PATH}:${LD_LIBRARY_PATH}"
	fi
fi 

GUEST_TARGET="${ARCH}-unknown-linux-musl"

# Run the unit tests first (this tests the testing framework itself not libkrun).
# Guest code may use Linux-only libc calls that won't compile with other toolchains.
if [ "$OS" = "Linux" ]; then
	cargo test -p test_cases --features guest
fi

# On macOS, we need to cross-compile for Linux musl
if [ "$OS" = "Darwin" ]; then
	SYSROOT="../linux-sysroot"
	if [ ! -d "$SYSROOT" ]; then
		echo "ERROR: Linux sysroot not found at $SYSROOT"
		echo "Run 'make' in the libkrun root directory first to create it."
		exit 1
	fi

	export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER="clang"
	export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_RUSTFLAGS="-C link-arg=-target -C link-arg=aarch64-linux-gnu -C link-arg=-fuse-ld=lld -C link-arg=--sysroot=$SYSROOT -C link-arg=-static"
	echo "Cross-compiling guest-agent for $GUEST_TARGET"

	# e2fsprogs is keg-only on macOS; add it to PATH for mke2fs.
	if [ -d "/opt/homebrew/opt/e2fsprogs/sbin" ]; then
		export PATH="/opt/homebrew/opt/e2fsprogs/sbin:$PATH"
	fi
fi

cargo build --target=$GUEST_TARGET -p guest-agent
cargo build -p runner

# On macOS, the runner needs entitlements to use Hypervisor.framework
if [ "$OS" = "Darwin" ]; then
	codesign --entitlements ../hvf-entitlements.plist --force -s - target/debug/runner
fi

export KRUN_TEST_GUEST_AGENT_PATH="target/$GUEST_TARGET/debug/guest-agent"

# Build runner args: pass through all arguments
RUNNER_ARGS="$*"

# Add --base-dir if KRUN_TEST_BASE_DIR is set
if [ -n "${KRUN_TEST_BASE_DIR}" ]; then
	RUNNER_ARGS="${RUNNER_ARGS} --base-dir ${KRUN_TEST_BASE_DIR}"
fi

target/debug/runner ${RUNNER_ARGS}
