#!/bin/sh

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

mkdir -p /run/runit/supervise
mkdir -p /run/runit/sv
# mount will fail in unprivileged container, see #1030225
#mount -t tmpfs -o size=20M,mode=0755 runtimesv /run/runit/sv
#cp -a /etc/sv/* /run/runit/sv/  #TODO do this with 'CPSV_DIR=/run/runit/sv cpsv --sync'

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=default
fi

# This script is also invoked in runit-systemd and runit-sysv packages.
# We must start sulogin and sysv scripts only if `runit` is current init
# system.
if [ -f /run/runit.stopit ] ; then
        # single mode
        if grep -q -w -i 'single' /proc/cmdline ; then
                chpst -P /sbin/sulogin -p /dev/tty1
        fi
        runsvchdir "$runsv_dir" || runsvchdir default

        # Give sysv scripts 90 seconds (hardcoded in async-timeout source) to
        # start. If something goes wrong, they are detached from controlling
        # terminal.
        #
        # In this case tty1 would likely look ugly -- output from sysv scripts
        # is written over terminal session, but at least we would be able to
        # login.

        if [ "$runsv_dir" != solo ] && [ ! -e /etc/runit/no.emulate.sysv ]; then
                /lib/runit/async-timeout /lib/runit/run_sysv_scripts '/etc/rc2.d'
        fi
else
        runsvchdir svmanaged
fi

if [ -x /sbin/vdevd ]; then
        while [ -n "$(lslocks -o command | grep "^vdev_modprobe$")" ]; do
                sleep 0.1
        done
        /lib/vdev/vdev_print_input_devices

        while [ -n "$(lslocks -o command | grep "^vdevd$")" ]; do
                sleep 0.1
        done
        if [ -n "$(ldconfig -p | grep libinput.so)" ]; then
                /lib/vdev/vdev_wait
        fi
fi

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

