#!/bin/sh

# https://www.qemu.org/docs/master/system/target-riscv.html#board-specific-documentation
# This is similar to the JH7110 used in the PineTab-V
EMU_MACHINE='sifive_u'
EMU_MEMORY='1G'
EMU_BIOS='none'
EMU_PLATFORM="-machine $EMU_MACHINE -smp 5 -m $EMU_MEMORY"
EMU_OPTIONS="-bios $EMU_BIOS -display none -serial stdio -gdb tcp::1234"
EMU_EXTRA=''
QEMU_BIN='qemu-system-riscv64'

kern_img=''

while [ "${1:-}" != "" ]; do
	case "$1" in
		"--debug")
			EMU_EXTRA='-S'
			;;
		"--dump-dts"|"--dump")
			# shellcheck disable=SC2086
			QEMU_CMD="$QEMU_BIN $EMU_PLATFORM $EMU_OPTIONS"
			$QEMU_CMD -machine dumpdtb=riscv64-"$EMU_MACHINE".dtb
			dtc riscv64-"$EMU_MACHINE".dtb > riscv64-"$EMU_MACHINE".dts
			exit 0
			;;
		*)
			kern_img="$1"
			;;
	esac
	shift
done


if ! [ "$kern_img" ]; then
	echo "Must provide kernel binary ($kern_img)"
	exit 1
fi

QEMU_CMD="$QEMU_BIN $EMU_PLATFORM $EMU_OPTIONS $EMU_EXTRA"

echo "starting $QEMU_CMD"
# shellcheck disable=SC2086
exec $QEMU_CMD -kernel "$kern_img"
