#!/bin/sh -e

nbd_device="/dev/nbd0"

help() {
echo "USAGE: qcow-mount <disk image>"
}

if [ -z "$1" ]; then
    help
    exit 1
fi
image="$1"
shift

fdisk_output=`sudo fdisk -l $nbd_device`
if [ ! -z "$fdisk_output" ]; then
    echo "An image is already associated with $nbd_device. Unmount and try again."
    exit 1
fi

if [ ! -s "$image" ]; then
    echo "Could not find image file. Aborting" >&2
    exit 1
fi

file "$image" | grep -q Qcow || {
    echo "'$image' is not a qcow file"
    exit 1
}

sudo modprobe nbd max_part=15
sudo qemu-nbd --connect=$nbd_device "$image"
sleep 1
device=`sudo fdisk -l $nbd_device | grep '83  Linux' | head -1 | awk '{print $1}'`
sleep 2
tmpdir=`mktemp -d`
sudo mount $device $tmpdir

echo "Mounted '$device' on '$tmpdir'"
echo "Unmount with:"
echo "$ qcow-umount '$tmpdir'"
