#!/usr/bin/env bash

if [ -z "$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
fi
processor="$PROCESSOR"

ACCEL=$(get_qemu_accelerator) ||
	exit $?

qemu=$(search_qemu_binary) ||
	exit $?

if ! $qemu -machine '?' 2>&1 | grep 'ARM Virtual Machine' > /dev/null; then
	echo "$qemu doesn't support mach-virt ('-machine virt'). Exiting."
	exit 2
fi

M='-machine virt'

if [ "$ACCEL" = "kvm" ]; then
	if $qemu $M,\? 2>&1 | grep gic-version > /dev/null; then
		M+=',gic-version=host'
	fi
	if [ "$HOST" = "aarch64" ] || [ "$HOST" = "arm" ]; then
		processor="host"
		if [ "$ARCH" = "arm" ] && [ "$HOST" = "aarch64" ]; then
			processor+=",aarch64=off"
		fi
	fi
fi

if ! $qemu $M -device '?' 2>&1 | grep virtconsole > /dev/null; then
	echo "$qemu doesn't support virtio-console for chr-testdev. Exiting."
	exit 2
fi

if $qemu $M -chardev testdev,id=id -initrd . 2>&1 \
		| grep backend > /dev/null; then
	echo "$qemu doesn't support chr-testdev. Exiting."
	exit 2
fi

chr_testdev='-device virtio-serial-device'
chr_testdev+=' -device virtconsole,chardev=ctd -chardev testdev,id=ctd'

pci_testdev=
if $qemu $M -device '?' 2>&1 | grep pci-testdev > /dev/null; then
	pci_testdev="-device pci-testdev"
fi

M+=",accel=$ACCEL"
command="$qemu -nodefaults $M -cpu $processor $chr_testdev $pci_testdev"
command+=" -display none -serial stdio -kernel"
command="$(timeout_cmd) $command"

run_qemu $command "$@"
