#!/bin/sh

if [ -z "$1" ]; then
	echo "mkhvmboot <disk>"
	exit 1
fi

disk=$1
valid=0
for d in `sysctl -n hw.disknames`
do
	[ "$d" = "$disk" ] && valid=1
done

if [ "$valid" = 0 ]; then
	echo "Disk $disk not found"
	exit 1
fi
gpt header $disk >/dev/null 2>&1
if [ "$?" = 0 ]; then
	# Has GPT header
	echo "Cleaning up existing GPT and wedges"
	wedges=`dkctl $disk listwedges | awk '{
		if ($1 ~ "^dk[0-9]*:") print substr($1, 1, length($1)-1)
	}'`
	for w in $wedges
	do
		dkctl $disk delwedge $w
	done
	gpt destroy $disk
fi

echo "Create GPT"
gpt create $disk || exit 1
gpt add -i 1 -b 64 -t efi -l efiboot $disk || exit 1

wedge=`dkctl $disk listwedges | awk '{
	if ($1 ~ "^dk[0-9]*:") {
		print substr($1, 1, length($1)-1)
		exit 0
	}
}'`

if [ -z "$wedge" ]; then
	echo "Could not find new wedge on $disk"
	exit 1
fi

newfs_msdos $wedge
mount NAME=efiboot /mnt || exit 1

mkdir -p /mnt/efi/boot /mnt/efi/NetBSD
cp /usr/mdec/bootx64.efi /mnt/efi/boot
sed -e 's/boot netbsd/boot hd1a:netbsd/' \
    -e 's;boot kernels/;boot hd1a:kernels/;' \
    -e 's;boot /kernels/;boot hd1a:kernels/;' \
	/boot.cfg > /mnt/efi/NetBSD/boot.cfg
umount /mnt

domid=$(xenstore-read "domid")
if [ -z "$domid" ]; then
	echo "Could not determine Xen domain ID"
	exit 1
fi
uu=$(xenstore-read /local/domain/$domid/vm)
if [ -z "$uu" ]; then
	echo "Coud not determine Xen VM UUID"
	exit 1
fi
uuid=${uu##*/}

echo "Run these commands on your XenServer host:"
echo
echo "xe vm-param-set uuid=$uuid domain-type=hvm"
echo "xe vm-param-set uuid=$uuid platform:viridian=false"
echo "xe vm-param-set uuid=$uuid HVM-boot-params:firmware=uefi"
echo "xe vm-param-set uuid=$uuid platform:device-model=qemu-upstream-uefi"
echo 'xe vbd-param-set uuid=$(xe vbd-list vm-uuid='$uuid' type=CD --minimal) userdevice=2'
