#!/bin/csh

set FREEBSD_PREFIX="/usr/data/sys/freebsd/"
set QEMU_PREFIX="/usr/local"

set QEMU="${QEMU_PREFIX}/bin/qemu"
set QEMU_X86_64="${QEMU_PREFIX}/bin/qemu-system-x86_64"
set QEMU_OPTIONS="-cpu qemu64,+smep,+smap -m 1024M"

set FREEBSD_VMIMAGE="freebsd-amd64.raw"
set FREEBSD_VMIMAGE_URL="http://ftp.freebsd.org/pub/FreeBSD/snapshots/VM-IMAGES/11.0-CURRENT/amd64/Latest/"

if (! -d ${FREEBSD_PREFIX}) then
	mkdir -p ${FREEBSD_PREFIX}
	if (! -d ${FREEBSD_PREFIX} )
		echo "fail... unable to create ${FREEBSD_PREFIX} dir"
		exit 1
	endif
endif

if (! -e ${FREEBSD_PREFIX}/${FREEBSD_VMIMAGE}) then
	set image=`fetch ${FREEBSD_VMIMAGE_URL} -o - | awk 'BEGIN{FS="\""} /raw/{print $4}'`
	set FREEBSD_VMIMAGE_URL=${FREEBSD_VMIMAGE_URL}/${image}
	fetch ${FREEBSD_VMIMAGE_URL} -o - | xzcat > ${FREEBSD_PREFIX}/${FREEBSD_VMIMAGE}
	echo ${FREEBSD_VMIMAGE_URL} > ${FREEBSD_PREFIX}/notes
endif


$QEMU_X86_64 $QEMU_OPTIONS -hda ${FREEBSD_PREFIX}/${FREEBSD_VMIMAGE}
