#!/bin/sh

if test -n "$DISPLAY" && test "$TERM" != xterm
then
    exec xterm -name qemu-win -title "Qemu Windows" -e "$0" "$@"
fi

if test "$(id -u)" != 0
then
    exec sudo "$0" "$@"
fi

export PULSE_SERVER=unix:/run/user/$SUDO_UID/pulse/native
export PULSE_COOKIE=/home/$SUDO_USER/.config/pulse/cookie
export QEMU_AUDIO_DRV=pa

# download ISO from http://www.android-x86.org/download and extract files with
#   7z x android-x86_64-8.1-r1.iso initrd.img kernel ramdisk.img system.sfs
# into DIR
DIR=$1
shift

# directory or image that gets mounted on /data in Android
if test -d "$1"
then
    kernel_arg='DATA=9p'
    data_opt="-virtfs local,id=data,mount_tag=data,security_model=passthrough,path=$1"
    shift
elif test -f "$1"
then
    kernel_arg='DATA=vdc'
    data_opt="-drive index=2,if=virtio,id=data,file=$1"
    shift
fi

exec qemu-system-x86_64 -name Android_x86 -enable-kvm \
  -kernel $DIR/kernel \
  -append "root=/dev/ram0 androidboot.selinux=permissive quiet console=ttyS0 RAMDISK=vdb $kernel_arg" \
  -initrd $DIR/initrd.img \
  -cpu host,kvm=off -smp 2 -m 2G -machine vmport=off \
  -usb -device usb-tablet \
  -serial stdio -parallel none \
  -drive index=0,if=virtio,id=system,file=$DIR/system.sfs,format=raw,readonly \
  -drive index=1,if=virtio,id=ramdisk,file=$DIR/ramdisk.img,format=raw,readonly \
  -nic user,id=net0,model=virtio-net-pci,hostname=android \
  -vga virtio -display gtk,gl=on \
  -soundhw hda \
  $data_opt \
  "$@"
