#!/bin/sh
#
# Set up a fusefile as a disk device using device mapper.
# Note that this requires root access.

if [ $(id -u) != 0 ] ; then
    echo "block device set up requires root." >&2
    exit 1
fi

# fuse blkdev mounting needs to sniff an existing but unmounted block
# device node for setup. However the device mapping has an empty table
# and the content is only accessible via the fuse mount that links it
# to the fusefile process. The device node (major:minor) are still
# considered in use by the kernel and, and the device node is "open"
# while mounted.

[ -e /dev/mapper/control ] || modprobe dm_mod || exit 1

# Create up to N fusedisk named as fusedisk0..fusediskN, the device
# mapper also creates its dm-X device nodes and we also force
# /dev/mapper/$NAME nodes for them.
N=15
DEV=
for I in $(seq 0 $N) ; do
    NAME=fusedisk$I
    C="$(dmsetup info --noheadings -c -o open $NAME 2>/dev/null)"
    if [ "$C" != "1" ] ; then
	if [ -z "$C" ] ; then
            dmsetup create $NAME --notable || exit 1
	    dmsetup mknodes $NAME || exit 1
	fi
	DEV=/dev/mapper/$NAME
	break
    fi
done
if [ -z "$DEV" ] ; then
    echo "** No more fusedisk devices" >&2
    exit 1
fi
echo "using $DEV for $*" | logger -t fusedisk
exec fusefile -oblkdev,fsname=$DEV -oallow_other $*
