#!/bin/sh -e

nbd_device="/dev/nbd0"

help() {
echo "USAGE: qcow-umount <directory>"
}

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

if [ ! -d "$image_dir" ]; then
    echo "Could not directory. Aborting" >&2
    exit 1
fi

sudo umount "$image_dir"
sleep 1
sudo nbd-client -d $nbd_device
fdisk_output=`sudo fdisk -l $nbd_device`
if [ ! -z "$fdisk_output" ]; then
    echo "Not properly unmounted:"
    echo "$fdisk_output"
    exit 1
fi

rmdir "$image_dir"

echo "SUCCESS"
exit 0
