#!/bin/sh

### configuration
ISO=${ISO:-fatdog.iso}
QEMU_AUDIO_DRV=${QEMU_AUDIO_DRV-alsa}
export QEMU_AUDIO_DRV
#CPUTYPE= # default is empty, can be "qemu64" (default) or "host" "kvm64" etc
CPUS=${CPUS:-1}
MEM=${MEM:-2048}
VGA_TYPE=${VGA_TYPE:-cirrus-vga} # or cirrus-vga (cirrus) or VGA (std)
#POINTER= # default is empty, can be usb-mouse, usb-tablet, or usb-wacom-tablet
MACH_TYPE=${MACH_TYPE:-pc}
QEMU_UI=${QEMU_UI:-sdl}
HOSTDVD=${HOSTDVD:+-drive if=scsi,file=/dev/$HOSTDVD,format=raw}
NIC=${NIC:-user,hostfwd=tcp::2222-:22}
UEFI_BIOS=${UEFI_BIOS:-uefi-bios.bin}
SOUNDHW=${SOUNDHW--device AC97}
NO_FLOPPY=${NO_FLOPPY--global isa-fdc.fdtypeA=none} # specify NO_FLOPPY= to enable floppy emulation
#SHARE=    # default is empty, but can be set to a path to share (read-only)
#SHARE_RW= # default is empty, but can be set to a path to share

DEVX_SFS=${DEVX_SFS:-fd64-devx.sfs}
NLS_SFS=${NLS_SFS:-fd64-nls.sfs}
BASE32_SFS=${BASE32_SFS:-32bit-fd64.sfs}

### helpers ###
sanitise() {
	case $QEMU_UI in
		sdl) export __GLX_VENDOR_LIBRARY_NAME=mesa # nvidia is problematic with sdl
	esac
}

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

###
sanitise
run_in_my_dir
case $1 in
	uefi) UEFI="-bios $UEFI_BIOS"; shift ;;
esac
case ${ISO##*.} in
	iso)
		[ -e $ISO ]          && HDC="-drive file=$ISO,index=2,media=cdrom -boot d"
		[ -e disk.ext3 ]     && HDA="-drive file=disk.ext3,index=0,media=disk,format=raw"
		;;
	img)
		[ -e $ISO ]          && HDA="-drive file=$ISO,index=0,media=disk,format=raw"
		[ -e disk.ext3 ]     && HDC="-drive file=disk.ext3,index=2,media=disk,format=raw"
		;;
esac
[ -e $NLS_SFS ]    && HDB="-drive file=$NLS_SFS,index=1,media=disk,format=raw"
[ -e $DEVX_SFS ]   && HDD="-drive file=$DEVX_SFS,index=3,media=disk,format=raw"
[ -e $BASE32_SFS ] && VDA1="-drive file=$BASE32_SFS,if=virtio,media=disk,format=raw"
[ -e disk2.img ]   && VDA2="-drive file=disk2.img,if=virtio,media=disk,format=raw"
[ "$HOSTDVD" ] && ! lsmod | grep -q ^sg && modprobe sg

# correct crazy mouse cursor under these two drivers
[ -z "$POINTER" ] &&
case $VGA_TYPE in
	virtio*|vmware-svga|qxl*) POINTER=usb-mouse ;;
esac
[ "$POINTER" ] && POINTER="-device $POINTER" # -usbdevice mouse/tablet/wacom-tablet for older qemu
[ "$CPUTYPE" ] && CPUTYPE="-cpu $CPUTYPE"
[ "$SHARE" ] && SHARE="-virtfs local,mount_tag=share,security_model=mapped,readonly=on,multidevs=remap,path=$SHARE"
[ "$SHARE_RW" ] && SHARE_RW="-virtfs local,mount_tag=share-rw,security_model=mapped,multidevs=remap,path=$SHARE_RW"

exec qemu-system-x86_64 -enable-kvm -machine $MACH_TYPE \
-display $QEMU_UI -m $MEM -device $VGA_TYPE $POINTER $CPUTYPE -smp $CPUS \
$UEFI -nic $NIC -usb $SOUNDHW \
$NO_FLOPPY $SHARE $SHARE_RW $HDA $HDB $HDD $VDA1 $VDA2 $HOSTDVD $HDC \
"$@"
