#!/usr/bin/openrc-run
# Copyright (c) 2025 The OpenRC Authors.
# See the Authors file at the top-level directory of this distribution and
# https://github.com/OpenRC/openrc/blob/HEAD/AUTHORS
#
# This file is part of OpenRC. It is subject to the license terms in
# the LICENSE file found in the top-level directory of this
# distribution and at https://github.com/OpenRC/openrc/blob/HEAD/LICENSE
# This file may not be copied, modified, propagated, or distributed
# except according to the terms contained in the LICENSE file.

# We currently start the s6 supervision tree as an
# openrc service. It's using ssd for now; we may
# switch to supervise-daemon later.

command="${RC_LIBEXECDIR}/sh/s6-svscanboot.sh"
command_args="$RC_SVCDIR"
command_background=yes
pidfile=/var/run/s6-svscan.pid
umask=022
# notify=fd:4  # when notify=fd is fixed, uncomment here and add -d4 in svscanboot

depend() {
	need localmount
}

_stop_and_crop() {
	if s6-svok "$1" 2>/dev/null ; then
		s6-svc -dwD -kx -- "$1"
	fi
	rm -rf -- "$1/supervise" "$1/event"
}

stop_post() {
	local scandir="$RC_SVCDIR/s6-scan" servicedirs="$RC_SVCDIR/s6-services"
	rm -rf -- "$scandir"
	if test -d "$servicedirs" ; then
		ebegin "Cleaning stray supervised processes"
		for i in `ls -1 "$servicedirs"` ; do
			_stop_and_crop "$servicedirs/$i" &
			if test -d "$servicedirs/$i/log" ; then
				_stop_and_crop "$servicedirs/$i/log" &
			fi
		done
		wait
		eend 0
		if test -d "$RC_CACHEDIR" ; then
			ebegin "Storing service directories in cache"
			rm -rf -- "$RC_CACHEDIR/s6-services"
			cp -pPR -- "$servicedirs" "$RC_CACHEDIR/"
			eend $?
		fi
	fi
}
