#!/bin/bash -eu

. /.initrd/initenv

. shell-error
. shell-locks

. uevent-sh-functions
. initrd-sh-functions

queuedir="$1"
QUEUE="${queuedir##*/}"
PROG="${QUEUE:--}: session=${SESSION:-0}: $PROG"
message_time=1

all_mounted()
{
	local eof fsdev fsdir

	while [ -z "${eof-}" ]; do
		read -r fsdev fsdir _ ||
			eof=1

		[ -n "$fsdev" ] && [ -d "$fsdir" ] ||
			continue

		if [ -n "${ROOTONLY-}" ]; then
			[ "$fsdir" = "$rootmnt" ] ||
				continue
		fi

		if ! mountpoint -q "$fsdir"; then
			message "$fsdir: Not mounted"
			return 1
		fi
	done < /etc/fstab

	message "$QUEUE: session=$SESSION: All mountpoints found"
}

sysinit_found()
{
	if chrooted "$rootmnt" test -e "$INIT"; then
		message "$QUEUE: session=$SESSION: system init ($INIT) found"
		return 0
	fi

	local msglock="/.initrd/polld/$PROG/message-shown"
	local deadline='/.initrd/rootdelay/deadline'
	local consmsg="/.initrd/rootdelay/message"

	[ ! -f "$deadline" ] ||
		echo 0 > "$deadline" ||:

	[ ! -d "$msglock" ] ||
		return 1

	mkdir -p -- "$msglock" ||:

	printf > "$consmsg" '%s\n' \
		"The init program \`$INIT' not found in the root directory."

	message "it looks like all mountpoints are ready, but \`$INIT' not found" \
	        "in the new root directory ($rootmnt)." \
	        "There is no point in waiting any longer."

	return 1
}

method=
{ read -r method < /etc/initrd/method; } >/dev/null 2>&1 ||:

while [ "$method" = localdev ]; do
	# postpone the events until the resume is checked.
	resume_checked ||
		exit 0

	all_mounted && sysinit_found ||
		break

	fd_lock 90 /dev/console

	message "$QUEUE: session=$SESSION: $method ready. acting!"

	echo 2 > /.initrd/telinit

	fd_unlock 90
	break
done

for e in "$1"/mount.*; do
	[ -e "$e" ] || break
	done_event "$e"
done
