#!/usr/bin/busybox sh
# shellcheck shell=busybox disable=SC3003

set -eo pipefail

SCRIPT_NAME="zfs-prepare-rootfs"
: ${LIB_DIR="/usr/lib/zfs/initcpio"}
# shellcheck source=zfs-functions
. "$LIB_DIR/zfs-functions"


#
# main
#

setup_debug

# The state file is loaded via systemd
if [[ ${ZFS_ROOT_MODE+set} ]]; then
	:
# if vars_present; then
# 	load_vars
# else
# 	parse_cmdline
else
	die "must be invoked with state variables in the environment"
fi

[[ ${ZFS_ROOT_MODE+set} ]] || die "internal: \$ZFS_ROOT_MODE not set"

case "$ZFS_ROOT_MODE" in
all)
	if dataset=$(zpool list -Ho bootfs | grep -m1 -vFx -); then
		ZFS_ROOT_POOL="${dataset%%/*}"
		ZFS_ROOT_DATASET="$dataset"
	else
		die "no pool with bootfs property found"
	fi
	;;

pool)
	[[ ${ZFS_ROOT_POOL+set} ]] || die "internal: \$ZFS_ROOT_POOL not set"

	if dataset=$(zpool list -Ho bootfs "$ZFS_ROOT_POOL" | grep -m1 -vFx -); then
		ZFS_ROOT_DATASET="$dataset"
	else
		die "no bootfs property found for pool \"$ZFS_ROOT_POOL\""
	fi
	;;

dataset)
	[[ ${ZFS_ROOT_POOL+set} ]] || die "internal: \$ZFS_ROOT_POOL not set"
	[[ ${ZFS_ROOT_DATASET+set} ]] || die "internal: \$ZFS_ROOT_DATASET not set"
	;;

*)
	die "invalid \$ZFS_ROOT_MODE=\"$ZFS_ROOT_MODE\""
	;;
esac

dump_vars

"$LIB_DIR/zfs-prepare-multiboot"

load_vars

if [[ "$ZFS_ROOT_MULTIBOOT" ]]; then
	log "multiboot configuration found in \"$ZFS_ROOT_POOL\", reloading" 5
	want_reload=1
fi
if zfs list -Ho name -d1 "$ZFS_ROOT_DATASET" | grep -q -v -Fx "$ZFS_ROOT_DATASET"; then
	log "nested datasets found under \"$ZFS_ROOT_DATASET\", reloading" 5
	want_reload=1
fi

if [[ "$want_reload" ]]; then
	systemctl daemon-reload

	# XXX: initrd-fs.target is enqueued before we have a chance to parse the pool,
	#      and thus it does not consider the new dependencies (nested datasets)
	#      we just wrote above during the daemon-reload call as part of the
	#      transaction. I do not know how this is supposed to work
	#      (initrd-parse-etc.service, which is the non-zfs equivalent
	#      to "parse nested filesystems", is executed even _later_).
	#      Try to reenqueue the unit.
	systemctl restart --no-block initrd-fs.target
fi

log "done"
exit 0

# vim: ft=bash ts=8 noet:
