#!/usr/bin/env bash

get_qemu_machine ()
{
	if [ "$MACHINE" ]; then
		echo $MACHINE
	else
		echo pseries
	fi
}

if [ -z "$KUT_STANDALONE" ]; then
	if [ ! -f config.mak ]; then
		echo "run ./configure && make first. See ./configure -h"
		exit 2
	fi
	source config.mak
	source scripts/arch-run.bash
	source scripts/vmm.bash
fi

set_qemu_accelerator || exit $?

MACHINE=$(get_qemu_machine) ||
	exit $?

if [[ "$MACHINE" == "powernv"* ]] && [ "$ACCEL" = "kvm" ]; then
	echo "PowerNV machine does not support KVM. ACCEL=tcg must be specified."
	exit 2
fi

qemu=$(search_qemu_binary) ||
	exit $?

if ! $qemu -machine '?' 2>&1 | grep $MACHINE > /dev/null; then
	echo "$qemu doesn't support '-machine $MACHINE'. Exiting."
	exit 2
fi

A="-accel $ACCEL$ACCEL_PROPS"
M="-machine $MACHINE"
B=""
D=""

if [[ "$MACHINE" == "pseries"* ]] ; then
	if [[ "$ACCEL" == "tcg" ]] ; then
		M+=",cap-cfpc=broken,cap-sbbc=broken,cap-ibs=broken,cap-ccf-assist=off"
	elif [[ "$ACCEL" == "kvm" ]] ; then
		M+=",cap-ccf-assist=off"
	fi
	B+="-bios $FIRMWARE"
fi

if [[ "$MACHINE" == "powernv"* ]] ; then
	D+="-device ipmi-bmc-sim,id=bmc0 -device isa-ipmi-bt,bmc=bmc0,irq=10"
fi

command="$qemu -nodefaults $A $M $B $D"
command+=" -display none -serial stdio -kernel"
command="$(panic_cmd) $(migration_cmd) $(timeout_cmd) $command"

# powerpc tests currently exit with rtas-poweroff, which exits with 0.
# run_test treats that as a failure exit and returns 1, so we need
# to fixup the fixup below by parsing the true exit code from the output.
# The second fixup is also a FIXME, because once we add chr-testdev
# support for powerpc, we won't need the second fixup.
run_test_status $command "$@"
