#!/bin/bash
# disconnects a VHD device from linux (should be unmounted)
# nbd-unmount path-to-vhd
DRIVE="$1"
QEMU_NBD_COMMAND="ps aux|grep '[q]emu-nbd.*--connect='|tr -s ' '|cut -f 11- -d ' '"

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

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

# iterate over all mounted nbds
NBD_TARGET=
while read MOUNT; do
	if echo "$MOUNT" | egrep "$DRIVE$" > /dev/null; then
		NBD_TARGET="$(echo "$MOUNT" | sed -E 's!.*(--connect=?|-c\s+)([^[:space:]]+).*!\2!g')"
	fi
done < <(eval "$QEMU_NBD_COMMAND")

if [ -z "$NBD_TARGET" ]; then
	echo "$DRIVE not mounted"
	exit 1
fi

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

qemu-nbd --disconnect=$NBD_TARGET
