#!/bin/dash

### configuration
CPUS=${CPUS:-1}
MEM=${MEM:-1024}
VGA_TYPE=${VGA_TYPE:-cirrus} # or std, or vmware (broken)
BOOT_PARAM=${BOOT_PARAM:-basesfs=device:sda:/ pfix=nox video=800x600-24} # or VGA-1:800x600-24
USESDL=${USESDL--sdl}
HOSTDVD=${HOSTDVD:+-drive if=scsi,file=/dev/$HOSTDVD,format=raw}
FATDOG_INITRD=${FATDOG_INITRD:-../pkg/000/fatdog-initrd}
NIC=${NIC:-user,hostfwd=tcp::2222-:22}
UEFI_BIOS=${UEFI_BIOS:-uefi-bios.bin}
SOUNDHW=${SOUNDHW--soundhw ac97}
#KVER= # default is empty
KERNEL=${KERNEL:-../kernel/vmlinuz}
MODULES=${MODULES:-../kernel/kernel-modules.sfs}
INITRD=${INITRD:-qemu-initrd}

### helpers ###
run_in_my_dir() {
	mydir=$(readlink -f "$0")
	mydir=${mydir%/*}
	cd $mydir
}

die() {
	echo "$1"
	exit 
}

build_initrd() {
	local INITRD_TMP INITRD_OUT

	# easier way to set kernels than individual spec of KERNEL, MODULES and INITRD
	if [ "$KVER" ]; then
		KERNEL=${KERNEL}-$KVER
		MODULES=${MODULES}-$KVER
		INITRD=${INITRD}-$KVER
	fi

	# kernel or modules don't exist, bail out
	! [ -e $KERNEL ] && die "$KERNEL doesn't exist"
	! [ -e $MODULES ] && die "$MODULES doesn't exist"

	# initrd doesn't exist, make one
	if ! [ -e $INITRD ]; then
		INITRD_TMP=/tmp/initrd.$$ INITRD_OUT=$(readlink -f "$INITRD")
		cp -a "$FATDOG_INITRD" $INITRD_TMP
		cp $MODULES $INITRD_TMP/kernel-modules.sfs
		find $INITRD_TMP -name placeholder_for_fossil -delete
		( cd $INITRD_TMP; find . | cpio -o -H newc > $INITRD_OUT )
		rm -rf $INITRD_TMP
	fi
}

### main ###
run_in_my_dir
build_initrd
case $1 in
	uefi) UEFI="-bios $UEFI_BIOS"; shift ;;
esac
[ -e fd64-nls.sfs ]  && HDB="-drive file=fd64-nls.sfs,index=1,media=disk,format=raw"
[ -e fd64-devx.sfs ] && HDC="-drive file=fd64-devx.sfs,index=2,media=disk,format=raw"
[ -e disk.ext3 ]     && HDD="-drive file=disk.ext3,index=3,media=disk,format=raw"
[ "$HOSTDVD" ] && ! lsmod | grep -q ^sg && modprobe sg

exec qemu-system-x86_64 -enable-kvm -soundhw hda \
$USESDL -m $MEM -vga $VGA_TYPE -smp $CPUS \
$UEFI -nic $NIC -usb $SOUNDHW \
-kernel $KERNEL -initrd $INITRD \
-append "$BOOT_PARAM $*" \
-drive file=fd64.sfs,index=0,media=disk,format=raw \
$HDB $HDC $HDD $HOSTDVD
