#!/usr/bin/env /lib/runit/invoke-run
#Copyright: 2022 Lorenzo Puliti <plorenzo@disroot.org>
#           2026 Aitor <aitor@genuen.org>
#License: CC0-1.0
#Comment: mdadm --monitor; idle if nothing to watch (avoid console restart storm)
#Comment: do not exec sv pause — that dies by signal on force-stop (finish -1)

[ -f /etc/default/mdadm ] && . /etc/default/mdadm
[ "$START_DAEMON" = true ] || exit 161
test -f /proc/mdstat || exit 162

has_redundant_md() {
	grep -qE '^md[0-9].*(raid([1-6]|10)|multipath)' /proc/mdstat 2>/dev/null
}

# Assemble may lag; wait briefly before giving up.
i=0
while [ "$i" -lt 15 ]; do
	has_redundant_md && break
	sleep 1
	i=$((i + 1))
done
unset i

# Stay up quietly until sv down / force-stop; exit 0 so finish is clean.
idle_until_down() {
	trap 'exit 0' TERM INT HUP
	while :; do
		sleep 86400 &
		wait $! || true
	done
}

if ! has_redundant_md; then
	# No RAID to monitor: stay quiet (do not restart-spam the console).
	idle_until_down
fi

mkdir -p /run/mdadm

exec 2>&1

# Run without exec so we can idle if monitor exits (e.g. arrays gone).
##bin## --monitor --scan $DAEMON_OPTIONS &
pid=$!
trap 'kill -TERM "$pid" 2>/dev/null; wait "$pid" 2>/dev/null; exit 0' TERM INT
wait "$pid" || true
unset pid

if has_redundant_md; then
	exit 1
fi
idle_until_down
