#!/bin/bash -eu

. shell-error
. initrd-sh-functions
. uevent-sh-functions
. /.initrd/initenv

PROG="${QUEUE:--}: session=${SESSION:-0}: $PROG"
message_time=1

pidfile="/var/run/$PROG.pid"
tsfile=/.initrd/md-raid-timeout
delay="${RAID_MEMBER_DELAY-}"

for e in "$1"/md-raid-member.*; do
	done_event "$e" ||:
done

[ -n "$delay" ] && [ "$delay" -gt 0 ] ||
	exit 0

now="$(timestamp boottime raw)"
now="${now%.*}"
echo "$(($now + $delay))" > "$tsfile"

[ ! -e "$pidfile" ] ||
	exit 0

is_raid()
{
	local MD_UUID='' MD_DEVICES='' MD_METADATA='' MD_DEVNAME='' MD_NAME=''

	# shellcheck disable=SC2046
	eval $(mdadm --detail --export "/dev/block/$1")

	[ -n "$MD_UUID" ] && [ -f "/etc/initrd/md/${MD_UUID//:}" ] ||
		return 1
}

(
	while :; do
		now="$(timestamp boottime raw)"
		now="${now%.*}"

		ts=
		readline ts "$tsfile"

		[ "$ts" -ge "$now" ] ||
			break
		sleep 1
	done

	# inactive mdraid salvation (#28879)
	inactive=
	for md in /sys/block/*/md/array_state; do
		[ -e "$md" ] ||
			break

		dev=
		readline dev "${md%/md/array_state}/dev"

		is_raid "$dev" ||
			continue

		state=
		readline state "$md"

		[ "$state" != "inactive" ] ||
			inactive=1
	done

	[ -z "$inactive" ] ||
		mdadm -IRs ||:

	for md in /sys/block/*/md/array_state; do
		[ -e "$md" ] ||
			break

		state=
		readline state "$md"

		[ "$state" = "read-auto" ] ||
			continue

		dev=
		readline dev "${md%/md/array_state}/dev"

		is_raid "$dev" ||
			continue

		mdadm -w "/dev/block/$dev" ||:
	done
) &

echo "$!" > "$pidfile"

