#!/bin/bash
# readies a VHD device in Linux
# nbd-mount /path/to/vhd /dev/nbd0
APP_DIR="$(dirname "$0")"
DRIVE="$1"
DISK_LABEL="$2"
DISK_PATH="/dev/disk/by-label/$DISK_LABEL"
SLEEP_INTERVAL=0.5

# refuse to connect twice
EXISTING_DRIVE="$(losetup -l | tail -n +2 | tr -s ' ' | cut -f 6 | grep -w "$DRIVE")"
if [ -n "$EXISTING_DRIVE" ]; then
	EXISTING_LOOP="$(losetup -l | tail -n +2 | tr -s ' ' | grep -w "$DRIVE" | cut -f 1 -d ' ')"
	if ! [ -L "$DISK_PATH" ] || ! [ -b "$DISK_PATH" ]; then
		echo "$DRIVE already mounted to $EXISTING_LOOP"
		exit 1
	fi
	LOOP_DEST="$(readlink -f $DISK_PATH)"
	if [ "$LOOP_DEST" != "$EXISTING_LOOP" ]; then
		echo "$DRIVE already mounted to $EXISTING_LOOP"
		exit 1
	fi

	# it's already mounted to the same destination
	exit 0
fi

# wait for device to appear
if ! [ -e "$DISK_PATH" ]; then
	losetup -f "$DRIVE"

	# poll until the block device node appears or task times out
	until [ -L "$DISK_PATH" ] && [ -b "$DISK_PATH" ]; do
		sleep "$SLEEP_INTERVAL"
	done
fi
