#!/bin/sh
# Advance runsvdir through service tiers (parallel within each tier).
# Called from stage 2 after the initial tier is already active.

set -e

initial=${1:-default}

waves_enabled=0
if [ -f /etc/runit/runsvdir-waves.enabled ] || [ -f /etc/runit/native.boot.run ]; then
	waves_enabled=1
fi
[ "$waves_enabled" = 1 ] || exit 0

trigger_rescan() {
	cur=
	if [ -r /etc/runit/runsvdir/current ]; then
		cur=$(readlink -f /etc/runit/runsvdir/current 2>/dev/null) || true
	fi
	if [ -n "$cur" ] && [ -d "$cur" ]; then
		: > "$cur/.forced-rescan" 2>/dev/null || true
	fi
}

for tier in 01-core 02-net default; do
	dir=/etc/runit/runsvdir/$tier
	[ -d "$dir" ] || continue

	if [ "$tier" = "$initial" ]; then
		/lib/runit/wait-tier "$tier" || true
		continue
	fi

	if [ -z "$(find "$dir" -maxdepth 1 -type l -print -quit 2>/dev/null)" ]; then
		continue
	fi

	runsvchdir "$tier" || continue
	trigger_rescan
	sleep 1
	/lib/runit/wait-tier "$tier" || true
done

if [ "$initial" != default ] && [ -d /etc/runit/runsvdir/default ]; then
	if [ -n "$(find /etc/runit/runsvdir/default -maxdepth 1 -type l -print -quit 2>/dev/null)" ]; then
		runsvchdir default || true
		trigger_rescan
	fi
fi

exit 0
