#!/bin/bash
# set -o xtrace
export BACKGROUND=';'
export MOUNT_PARENT_BLOCK=/issue54
export MOUNT_PARENT_POOL=/issue54

export BASENAME=issue54

# in MB, +_1:
export DEVBLOCKUNIT=1M
export DEVCAPACITY=$((64*1))
export DEVPREALLOC=0
# export OPTS="-O dedup=on -O compression=lzjb"
# export OPTS="-o version=13"
# export DAEMON_OPTIONS="--no-kstat-mount -a 1 -e 1"

export VDEVTYPE=""
export POOLS="demo"
export PARENTS="a"
export CHILDREN="$(seq 1 1)"

if [[ $# -gt 0 ]]; then export VDEVTYPE="$1"; shift; fi
if [[ $# -gt 0 ]]; then export PARENTS="$1"; shift; fi
if [[ $# -gt 0 ]]; then export CHILDREN="$1"; shift; fi
if [[ $# -gt 0 ]]; then export OPTS="$@"; fi

pgrep zfs-fuse && for POOL in $POOLS
do
	while ! zpool destroy "$BASENAME$POOL"; do sleep .1; done
done

echo =========== EXPORT/DESTROY done ==============
mount | grep fuse
# read

# derived vars
if [[ $DEVPREALLOC -le 0 ]]; then export DEVPREALLOC=1; fi
if [[ $DEVPREALLOC -gt $DEVCAPACITY ]]; then export DEVPREALLOC="$DEVCAPACITY"; fi

# restart zfs-fuse
if [[ "x" == "x$ZFS_GDB" ]]; then
    echo "forced clean relaunch of zfs-fuse"
    (
        /etc/init.d/zfs-fuse restart
    ) &
else
    echo "keeping zfs daemon (being debugged)"
fi

for POOL in $POOLS
do
	export POOLNAME="$BASENAME$POOL"
	export blockdir=$MOUNT_PARENT_BLOCK/${POOLNAME}_blk
	echo ======== building pool $POOL named $POOLNAME at $blockdir =================================

	mkdir -p "$blockdir"

	# create backing files
	rm -f "$blockdir"/z*
	for parent in $PARENTS
	do 
		{
			for m in $CHILDREN
			do
				dd if=/dev/zero bs=$DEVBLOCKUNIT seek=$(($DEVCAPACITY-$DEVPREALLOC)) count=$DEVPREALLOC of="$blockdir/z$parent$m" 2> /dev/null
			done&
			wait;
		}
	done

	while [[ ! -f /var/lock/zfs/zfs_lock || ! -S /var/run/zfs/zfs_socket ]]; do
	    if [[ -S /etc/zfs/zfs_socket ]]; then echo ANCIENT zfs daemon!; break; fi
	    sleep 0.5; echo waiting for zfs-fuse...
	done

	# create pool and list status
	layout=""
	for parent in $PARENTS
	do
		layout="$layout $VDEVTYPE"
		for m in $CHILDREN
		do
			layout="$layout $blockdir/z$parent$m"
			#break
		done
	done

	echo zpool create -O mountpoint="$MOUNT_PARENT_POOL/$POOLNAME" "$POOLNAME" $OPTS $layout
	zpool create $OPTS -O mountpoint="$MOUNT_PARENT_POOL/$POOLNAME" "$POOLNAME" $layout
done
wait
zpool status -v
zfs list

# zpool destroy "$POOLNAME" && killall zfs-fuse

