#!/bin/sh


DEBUG="_debug"
QEMU="$HOME/pkg/bin/qemu-system-x86_64"
#QEMU_ARGS="-m 512 -accel hvf -display none -serial stdio"
#QEMU_ARGS="-m 512 -accel hvf -serial stdio"
QEMU_ARGS="-m 1024 -accel hvf -display none -serial stdio"
#QEMU_ARGS="$QEMU_ARGS -gdb tcp::1234 -S"
#KERNEL="netbsd"
#RAMDISK="ramdisk.fs"
#RAMDISK="ramdisk-cgdroot.fs"
RAMDISK="rescue-amd64.img"
#RAMDISK="miniroot.kmod,cgdroot.kmod"
#RAMDISK="miniroot.kmod"
#RAMDISK="cgdroot.kmod"
#RAMDISK="../artwork/splash/yrmt-splash-1024x768-01.png"
#APPEND="console=com0"
#APPEND="bootdev=ld0a root=/dev/md0a rw -v"
#APPEND="root=md0a console=com rw -v"
#APPEND="console=com rw -v -x"
APPEND="console=com rw -x"
#APPEND="console=com rw -q"
#APPEND="rw -v"
DISKFILE="ld0.img"


#debug
_debug()
{
	echo "$@"
	"$@"
}


[ -f "$DISKFILE" ] || dd if=/dev/zero of="$DISKFILE" bs=1k oseek=3999999 count=1

_generic()
{
	QEMU_ARGS="$QEMU_ARGS -cpu host"
	#QEMU_ARGS="$QEMU_ARGS -drive if=pflash,format=raw,readonly=on,file=$HOME/pkg/share/ovmf/OVMFX64.fd"
	#QEMU_ARGS="$QEMU_ARGS -bios $HOME/pkg/share/qemu/edk2-x86_64-code.fd"
	#QEMU_ARGS="$QEMU_ARGS -drive if=pflash,format=raw,readonly=on,file=$HOME/pkg/share/qemu/edk2-x86_64-code.fd"
	#APPEND="rw -v"
	KERNEL="netbsd-GENERIC"
	$DEBUG $QEMU $QEMU_ARGS -kernel "$KERNEL" -append "$APPEND" -initrd "$RAMDISK" \
		-action reboot=shutdown -D qemu.log -d cpu_reset,in_asm,guest_errors,unimp \
		-drive file="$DISKFILE",format=raw,if=virtio
}

_microvm()
{
	#QEMU_ARGS="$QEMU_ARGS -M microvm,rtc=on,acpi=off,pic=off"
	QEMU_ARGS="$QEMU_ARGS -M microvm,rtc=off,acpi=off,pic=off"
	KERNEL="netbsd-MICROVM"
	APPEND="$APPEND plus_a_test=1.2.3.4"
	$DEBUG $QEMU $QEMU_ARGS -kernel "$KERNEL" -append "$APPEND" -initrd "$RAMDISK" \
		-action reboot=shutdown -D qemu.log -d cpu_reset,in_asm,guest_errors,unimp \
		-device virtio-blk-device,drive=hd0 -drive file="$DISKFILE",format=raw,id=hd0
}

_zfsinstall()
{
	RAMDISK="NetBSD-11.0_RC1-amd64.iso"
	QEMU_ARGS="-m 1024 -accel hvf"
	QEMU_ARGS="$QEMU_ARGS -cpu host -boot d"

	$DEBUG $QEMU $QEMU_ARGS \
		-cdrom "$RAMDISK" \
		-drive file="$DISKFILE",format=raw,id=hd0
}

_zfsnetinstall()
{
	RAMDISK="boot.iso"
	QEMU_ARGS="-m 2048 -accel hvf"
	QEMU_ARGS="$QEMU_ARGS -cpu host -boot d"

	$DEBUG $QEMU $QEMU_ARGS \
		-cdrom "$RAMDISK" \
		-drive file="$DISKFILE",format=raw,id=hd0
}

_zfsnetinstall_com()
{
	RAMDISK="boot-com.iso"
	QEMU_ARGS="-m 2048 -accel hvf -display none -serial stdio"
	QEMU_ARGS="$QEMU_ARGS -cpu host -boot d"

	$DEBUG $QEMU $QEMU_ARGS \
		-cdrom "$RAMDISK" \
		-drive file="$DISKFILE",format=raw,id=hd0
}

#_generic
_microvm
#_zfsinstall
#_zfsnetinstall
#_zfsnetinstall_com

#qemu -gdb tcp::1234 -S
#(gdb) target remote :1234
#(gdb) p start_pvh
#(gdb) b *0x20b440
#(gdb) si
#(gdb) x/20wx 0x...
#0xffffffff80000000 is KERNBASE
