#!/bin/bash
# disconnects a VHD device from linux (should be unmounted)
# nbd-unmount path-to-vhd
DRIVE="$1"

if [ -z "$DRIVE" ]; then
	echo "Drive not provided"
	exit 1
fi

if ! [ -f "$DRIVE" ]; then
	echo "$DRIVE not existing"
	exit 1
fi

EXISTING_DRIVE="$(losetup -l | tail -n +2 | tr -s ' ' | cut -f 6 | grep -w "$DRIVE")"
if [ -z "$EXISTING_DRIVE" ]; then
	echo "$DRIVE not mounted"
	exit 1
fi

EXISTING_LOOP="$(losetup -l | tail -n +2 | tr -s ' ' | grep -w "$DRIVE" | cut -f 1 -d ' ')"
LOOP_DEST="$(readlink -f $EXISTING_LOOP)"

if mount | grep ^"$LOOP_DEST" -q ; then
	echo "$LOOP_DEST mounted, refusing to detach"
	exit 1
fi

losetup -d "$LOOP_DEST"
