#!/bin/bash
# returns an unused nbd device
for sys_path in /sys/block/nbd[0-9]*; do
	[ -d "$sys_path" ] || continue

	if [ -f "$sys_path/size" ] && [ "$(< "$sys_path/size")" -eq 0 ] ; then
		TARGET="/dev/${sys_path##*/}"
		break
	fi
done

if [ -z "$TARGET" ]; then
	echo "Error: no free NBD device found" >&2
	exit 1
fi

echo $TARGET
