#!/bin/sh

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/sbin:/usr/bin:/bin
SVDIR=/etc/service
export PATH

mkdir -p /run/runit/supervise
#sync available services
/lib/runit/trigger_sv setup

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

seed_merged_from_tier() {
	_tier=$1
	_src=/etc/runit/runsvdir/$_tier
	_dst=/etc/runit/runsvdir/merged
	mkdir -p "$_dst"
	[ -d "$_src" ] || return 1
	[ -n "$(find "$_src" -maxdepth 1 -type l -print -quit 2>/dev/null)" ] || return 1
	for _link in "$_src"/*; do
		[ -L "$_link" ] || continue
		_name=${_link##*/}
		case "$_name" in
			.*) continue ;;
		esac
		[ -e "$_dst/$_name" ] || [ -L "$_dst/$_name" ] && continue
		if [ -d "/etc/sv/$_name" ]; then
			ln -sf "/etc/sv/$_name" "$_dst/$_name"
		else
			ln -sf "$(readlink "$_link")" "$_dst/$_name"
		fi
	done
	unset _tier _src _dst _link _name
	return 0
}

pick_initial_runsvdir() {
	if [ "$waves_enabled" = 1 ]; then
		# Prefer phased boot: seed merged from 01-core (or first non-empty tier).
		for tier in 01-core 02-base default; do
			if seed_merged_from_tier "$tier"; then
				echo merged
				return 0
			fi
		done
	fi
	for tier in 01-core 02-base default; do
		dir="/etc/runit/runsvdir/$tier"
		if [ -d "$dir" ] && [ -n "$(find "$dir" -maxdepth 1 -type l -print -quit 2>/dev/null)" ]; then
			echo "$tier"
			return 0
		fi
	done
	echo default
}

if [ ! -z $runitdir ] && [ -d /etc/runit/runsvdir/"$runitdir" ]; then
	runsv_dir="$runitdir"
elif [ -r /etc/runit/default.runsvdir ]; then
	runsv_dir="$(cat /etc/runit/default.runsvdir)"
else
	runsv_dir="$(pick_initial_runsvdir)"
fi

# single/recovery mode
if grep -q -w -i 'single' /proc/cmdline ; then
	chpst -P /sbin/sulogin -p /dev/tty1
fi
runsvchdir "$runsv_dir" || runsvchdir default

if [ "$waves_enabled" = 1 ]; then
	/lib/runit/runsvdir-waves "$runsv_dir" &
fi

#sysv emulation
   #90 sec timeout (async timeout) for each script to start, then it detaches
   #to avoid getting stuck at boot. see #838480-msg#49
if [ "$runsv_dir" != solo ] && [ ! -e /etc/runit/no.emulate.sysv ]; then
	/lib/runit/async-timeout /lib/runit/run_sysv_scripts '/etc/rc2.d'
fi


exec env - PATH=$PATH \
runsvdir -P "${SVDIR}" 'log: ...........................................................................................................................................................................................................................................................................................................................................................................................................'
