#!/usr/bin/bash

if [ -z "$STRATIS_ROOTFS_UUID" ]; then
	echo STRATIS_ROOTFS_UUID is a required environment variable. >&2
	exit 1
fi

i=0
while [ "$(stratis-min pool all-devices-present "$STRATIS_ROOTFS_UUID" 2>/dev/null)" != true ]; do
	echo Waiting on all devices for pool with UUID $STRATIS_ROOTFS_UUID...
	sleep 1
	if [ "$i" = 5 ]; then
		break
	fi
	i=$(($i + 1))
done

if $(stratis-min pool all-devices-present "$STRATIS_ROOTFS_UUID"); then
	if $(stratis-min pool is-stopped "$STRATIS_ROOTFS_UUID"); then
		if $(stratis-min pool has-passphrase "$STRATIS_ROOTFS_UUID"); then
			ATTEMPTS_REMAINING=3
			if
				! while [ $((ATTEMPTS_REMAINING--)) -gt 0 ]; do
					systemd-ask-password --timeout=0 --id="stratis:$STRATIS_ROOTFS_UUID" "Enter password for Stratis pool with UUID $STRATIS_ROOTFS_UUID containing root filesystem" |
						stratis-min pool start --prompt --token-slot=any "$STRATIS_ROOTFS_UUID" && break
				done
			then
				echo Failed to start pool with UUID $STRATIS_ROOTFS_UUID using a passphrase >&2
				exit 1
			fi
		fi
		if ! $(stratis-min pool is-encrypted "$STRATIS_ROOTFS_UUID"); then
			if ! stratis-min pool start "$STRATIS_ROOTFS_UUID"; then
				echo Failed to start pool with UUID $STRATIS_ROOTFS_UUID >&2
				exit 1
			fi
		fi
	fi
else
	echo Could not find all devices for pool "$STRATIS_ROOTFS_UUID"
	exit 1
fi
