#!/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 is-stopped "$STRATIS_ROOTFS_UUID" >/dev/null; do
	echo Waiting on pool with UUID $STRATIS_ROOTFS_UUID...
	sleep 1
	if [ "$i" = 5 ]; then
		break
	fi
	i=$(($i + 1))
done

if $(stratis-min pool is-stopped "$STRATIS_ROOTFS_UUID"); then
	if $(stratis-min pool is-encrypted "$STRATIS_ROOTFS_UUID"); then
		ATTEMPTS_REMAINING=3
		if
			! while [ $((ATTEMPTS_REMAINING--)) -gt 0 ]; do
				systemd-ask-password --id="stratis:$STRATIS_ROOTFS_UUID" "Enter password for Stratis pool with UUID $STRATIS_ROOTFS_UUID containing root filesystem" |
					stratis-min pool start --prompt --unlock-method=keyring "$STRATIS_ROOTFS_UUID" && break
			done
		then
			echo Failed to start pool with UUID $STRATIS_ROOTFS_UUID using a passphrase >&2
			exit 1
		fi
	else
		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
