#!/usr/sbin/openrc-run
#
# Wait until all MD arrays are idle/synced before halt/reboot.
# Intended for the OpenRC shutdown/off runlevels (started on enter).
#

description="Wait for MD arrays to become idle"

MDADM="/sbin/mdadm"

depend() {
	after umountroot
	before halt reboot
}

# OpenRC starts services when entering shutdown/off; that is when we wait.
start() {
	[ -x "$MDADM" ] || return 0
	[ -f /proc/mdstat ] || return 0

	sync
	wait=
	for md in /sys/block/md*/md; do
		[ -d "$md" ] || continue
		[ "$wait" ] || ebegin "Waiting for MD arrays to become idle"
		wait=y
		[ -w "$md/sync_action" ] && echo idle > "$md/sync_action"
	done
	if [ "$wait" ]; then
		# mdadm --wait-clean has a short internal timeout
		if "$MDADM" --wait-clean --scan; then
			eend 0
		else
			eend 1
			sleep 1
		fi
	fi
	return 0
}

stop() {
	return 0
}
