#!/bin/bash
# set -o xtrace
export MOUNT_PARENT_BLOCK=/mnt
export MOUNT_PARENT_POOL=/mnt

export BASENAME=dorky

# in MB, +_1:
export DEVBLOCKUNIT=1M
export DEVCAPACITY=$((1024*512*3))
export DEVPREALLOC=0
export OPTS="-O compression=gzip-9"

export VDEVTYPE="raidz2"
export POOLS="1 2 3 4 5"
export PARENTS="a b c d"
export CHILDREN="$(seq 1 35)"

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

for POOL in $POOLS
do
	export POOLNAME="$BASENAME$POOL"
	zpool destroy "$POOLNAME" || true
done

# 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"
    (
        killall zfs-fuse
        sleep 0.5; 
        killall -9 zfs-fuse; 
        rm -f /etc/zfs/zpool.cache /var/lock/zfs/zfs_lock /var/run/zfs/zfs_socket; 
        zfs-fuse; 
        sleep 1
    )&
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 names $POOLNAME at $blockdir =================================

	# mount block loopfile backing on tmpfs
	# if [[ 0 -eq $((for escaped_fs in $(cut -d\  -f2 /proc/mounts); do /bin/echo -e "$escaped_fs"; done) | grep "^$blockdir" | wc -l) ]]; then
	#     echo "mounting $blockdir..."
	#     mkdir -p "$blockdir"
	#     mount -t tmpfs none "$blockdir"
	# else
	#     echo "$blockdir already mounted"
	# fi

	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&
	done

	wait # apparently there can be races with zfs-fuse... I thought removing zpool.cache would prevent this...

	while [[ ! -f /var/lock/zfs/zfs_lock || ! -S /var/run/zfs/zfs_socket ]]; do
	    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="/tmp/$POOLNAME" "$POOLNAME" $OPTS $layout
	zpool create $OPTS -O mountpoint="/tmp/$POOLNAME" "$POOLNAME" $layout
	zpool status -v
done
zfs list

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

