#!/bin/sh
exec 2>&1

PATH=/usr/sbin:/sbin:/usr/bin:/bin
export PATH

LAST=0

# While test -x is more natural, it does not consider file with
# executable bit set on 'noexec' filesystem as executable, and /run
# often is mounted as 'noexec'.
[ $(stat -c %a /run/runit.reboot) = 100 ] && LAST=6
# used by /sbin/runlevel
printf "$LAST" >/run/runit.runlevel

[ -x /etc/runit/rc.shutdown ] && /etc/runit/rc.shutdown

echo 'Waiting for services to stop...'
sv -w 25 force-stop /etc/service/*
sv exit /etc/service/*

echo 'Running shutdown tasks...'

# Early *-stop oneshots (NN 00–49). Does not replace SysV.
if [ -f /etc/runit/native.boot.run ]; then
	[ -r /etc/runit/shutdown-run/05-shutdown-oneshots.sh ] && . /etc/runit/shutdown-run/05-shutdown-oneshots.sh
fi

# Native shutdown-run (umount/halt/…) when present beyond oneshot helpers;
# otherwise the SysV K* path — same else as before.
_shutdown_native=0
if [ -f /etc/runit/native.boot.run ] && [ -d /etc/runit/shutdown-run ]; then
	for f in /etc/runit/shutdown-run/*.sh; do
		[ -e "$f" ] || break
		case ${f##*/} in
			05-shutdown-oneshots.sh|85-shutdown-oneshots-late.sh) continue ;;
		esac
		_shutdown_native=1
		[ -r "$f" ] && . "$f"
	done
fi
if [ "$_shutdown_native" = 0 ]; then
	/lib/runit/run_sysv_scripts "/etc/rc$LAST.d" stop
fi
unset _shutdown_native f

# Late *-stop oneshots (NN 50–99), after umount (SysV or native).
if [ -f /etc/runit/native.boot.run ]; then
	[ -r /etc/runit/shutdown-run/85-shutdown-oneshots-late.sh ] && . /etc/runit/shutdown-run/85-shutdown-oneshots-late.sh
fi
