#!/bin/sh
set -eu
what="$(systemctl show -P What sysroot.mount)"
opts="$(systemctl show -P Options sysroot.mount)"

# Catch cases where sysroot isn't a device,
# especially kiwi's install:CDLABEL=INSTALL syntax.
if ! echo "$what" | grep -q ^/; then
	echo "Unable to detect firstboot on $what" >&2
	exit 0
fi

mount -o "$opts" "$what" /sysroot

if ! [ -e /sysroot/etc/machine-id ] \
	|| grep -qw 'ignition\.firstboot' /proc/cmdline || grep -qw 'catalyst\.firstboot' /proc/cmdline; then
	echo "Firstboot detected"
	if [ "$(uname -m)" = "s390x" ]; then
		# On s390x, attached DASDs need to be enabled first to appear as block devices.
		# On the first boot this is necessary to probe for configuration sources.
		echo "Trying to enable all available DASDs"
		chzdev dasd --offline --existing --enable --active || echo "Couldn't enable all DASD devices, trying to continue anyway." >&2
	fi
	# Make initrd.target require firstboot.target
	systemctl enable --quiet firstboot.target
	# As initrd.target/start was already scheduled, ^ does not have any immediate effect.
	# Triggering a start of initrd.target again schedules the missing jobs.
	# With --job-mode=fail this fails if any of those missing jobs is destructive, likely
	# caused by dep cycles in firstboot units.
	systemctl start --now --no-block --job-mode=fail initrd.target
fi
