#!/usr/bin/env bash

# Copyright 2016 The Fuchsia Authors
# Copyright (c) 2008 Travis Geiselbrecht
#
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT

function HELP {
    echo "help:"
    echo "-a                  : add intel hda sound"
    echo "-b                  : a virtio block device"
    echo "-c                  : cmpctmalloc instead of dlmalloc"
    echo "-M                  : miniheap instead of dlmalloc"
    echo "-n                  : a virtio network device"
    echo "-t                  : a virtio tap network device"
    echo "-d                  : a virtio display"
    echo "-3                  : cortex-m3 based platform"
    echo "-6                  : 64bit arm"
    echo "-m <memory in MB>"
    echo "-s <number of cpus>"
    echo "-h for help"
    echo "all arguments after -- are passed to qemu directly"
    exit 1
}

DO_AUDIO=0
DO_BLOCK=0
DO_NET=0
DO_NET_TAP=0
DO_64BIT=0
DO_CORTEX_M3=0
DO_DISPLAY=0
DO_CMPCTMALLOC=0
DO_MINIHEAP=0
SMP=1
MEMSIZE=512
SUDO=""

while getopts abdhm:cMnt36s: FLAG; do
    case $FLAG in
        a) DO_AUDIO=1;;
        b) DO_BLOCK=1;;
        c) DO_CMPCTMALLOC=1;;
        d) DO_DISPLAY=1;;
        M) DO_MINIHEAP=1;;
        n) DO_NET=1;;
        t) DO_NET_TAP=1;;
        3) DO_CORTEX_M3=1;;
        6) DO_64BIT=1;;
        m) MEMSIZE=$OPTARG;;
        s) SMP=$OPTARG;;
        h) HELP;;
        \?)
            echo unrecognized option
            HELP
    esac
done

shift $((OPTIND-1))

if [ $DO_64BIT == 1 ]; then
    QEMU="qemu-system-aarch64 -machine virt -cpu cortex-a53"
    PROJECT="qemu-virt-a53-test"
elif [ $DO_CORTEX_M3 == 1 ]; then
    QEMU="qemu-system-arm -machine lm3s6965evb -cpu cortex-m3"
    PROJECT="lm3s6965evb-test"
else
    QEMU="qemu-system-arm -machine virt -cpu cortex-a15"
    PROJECT="qemu-virt-a15-test"
fi

ARGS=" -m $MEMSIZE -smp $SMP -kernel build-${PROJECT}/magenta.elf"

AUDIO_ARGS=" -soundhw hda"
BLOCK_ARGS=" -drive if=none,file=blk.bin,id=blk,format=raw -device virtio-blk-device,drive=blk"
NET_ARGS=" -netdev user,id=vmnic,hostname=qemu -device virtio-net-device,netdev=vmnic"
NET_TAP_ARGS=" -netdev tap,id=vmnic -device virtio-net-device,netdev=vmnic"
NO_DISPLAY_ARGS=" -nographic"
DISPLAY_ARGS=" -device virtio-gpu-device -serial stdio"

echo DO_BLOCK = $DO_BLOCK
echo DO_NET = $DO_NET

if [ $DO_AUDIO == 1 ]; then
    ARGS+=$AUDIO_ARGS
    export QEMU_AUDIO_DRV=none
fi
if [ $DO_BLOCK == 1 ]; then
    ARGS+=$BLOCK_ARGS
fi
if [ $DO_NET == 1 ]; then
    ARGS+=$NET_ARGS
fi
if [ $DO_NET_TAP == 1 ]; then
    ARGS+=$NET_TAP_ARGS
    SUDO="sudo "
fi
if [ $DO_DISPLAY == 1 ]; then
    ARGS+=$DISPLAY_ARGS
else
    ARGS+=$NO_DISPLAY_ARGS
fi

MAKE_VARS=""

if [ $DO_CMPCTMALLOC == 1 ]; then
	MAKE_VARS=LK_HEAP_IMPLEMENTATION=cmpctmalloc
elif [ $DO_MINIHEAP == 1 ]; then
	MAKE_VARS=LK_HEAP_IMPLEMENTATION=miniheap
fi

make $MAKE_VARS $PROJECT -j4 &&
echo $SUDO $QEMU $ARGS $@ &&
$SUDO $QEMU $ARGS $@
