#!/bin/sh

usage() {
  echo "Usage: $0 [--gui] --kernel=vmlinuz... --ramfs=initramfs --image=fsimage [--dtb=vexpress.dtb]"
  exit 1
}

GUI=0
while [ $# -ne 0 ]; do
    option=$1
    shift

    optarg=""
    case $option in
    --*=*)
        optarg=`echo $option | sed -e 's/^[^=]*=//'`
        ;;
    esac

    case $option in
    --debug)
        set -x
        ;;
    -h|--h*)
        usage
        ;;
    -x|--x|--gui)
        GUI=1
        ;;
    --k*)
        KERN=$optarg
        ;;
    --i*)
        IMAGE=$optarg
        ;;
    --r*)
        RAMFS=$optarg
        ;;
    --fdt*|--dtb*)
        FDT=$optarg
        ;;
    *)
        echo "${0}: Invalid argument \"$option\""
        usage
        exit 1
        ;;
    esac
done
 
if [ "$KERN" = "" ] || [ "$IMAGE" = "" ] || [ "$RAMFS" = "" ]; then
  usage
fi

if [ ! -f "$KERN" ]; then
  echo "Kernel $KERN not found"
  exit 1
fi
if [ ! -f "$RAMFS" ]; then
  echo "Initramfs $RAMFS not found"
  exit 1
fi
if [ ! -f "$IMAGE" ]; then
  echo "Filesystem image $IMAGE not found"
  exit 1
fi
if [ ! -f "$FDT" ]; then
  FDTARG=""
  KREV="`echo $KERN | sed -e 's/.*vmlinuz-\([0-9.-]*\).fc.*/\1/' -e 's/[.-]/0/g' | colrm 4`"
  if [ $KREV -gt 306 ]; then
    echo "Warning: Kernel versions 3.7+ require a dtb to boot. This will probably crash."
  fi
else
  FDTARG="-dtb $FDT"
fi
 
if [ -f /usr/bin/qemu-system-arm ]; then
  if [ $GUI = 1 ]; then
    qemu-system-arm -machine vexpress-a9 -m 1024 -net nic -net user \
      -append "rw root=/dev/mmcblk0p3 rootwait physmap.enabled=0" \
      -kernel "$KERN" \
      -initrd "$RAMFS" \
      -sd "$IMAGE" $FDTARG
  else
    qemu-system-arm -machine vexpress-a9 -m 1024 -nographic -net nic -net user \
      -append "console=ttyAMA0,115200n8 rw root=/dev/mmcblk0p3 rootwait physmap.enabled=0" \
      -kernel "$KERN" \
      -initrd "$RAMFS" \
      -sd "$IMAGE" $FDTARG
  fi
else
  echo "You need to install qemu-system-arm to boot a versatile express image"
  exit 1
fi


