diff --git a/bin/losetup-mount b/bin/losetup-mount new file mode 100755 index 0000000..3dfd5f2 --- /dev/null +++ b/bin/losetup-mount @@ -0,0 +1,36 @@ +#!/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 diff --git a/bin/losetup-unmount b/bin/losetup-unmount new file mode 100755 index 0000000..c76b790 --- /dev/null +++ b/bin/losetup-unmount @@ -0,0 +1,30 @@ +#!/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"