#!/usr/bin/env /lib/runit/invoke-run
#Copyright: 2026 Aitor <aitor@genuen.org>
#License: CC0-1.0
#Comment: supervised vdevd (-f). First boot is early; coldplug promotes.
#Comment: A later sv restart execs long-running if that promote already happened.
#Comment: env from stage-1 boot-run (/run/vdev/env); KMS also stage-1
#Comment: vdev-coldplug.sh is a sibling 01-core oneshot (waits for control)

exec 2>&1

if [ -r /run/vdev/env ]; then
	# shellcheck disable=SC1091
	. /run/vdev/env
elif [ -r /lib/vdev/vdev-env.sh ]; then
	# shellcheck disable=SC1091
	. /lib/vdev/vdev-env.sh
else
	exit 162
fi

[ -x "${VDEV_BIN}" ] || exit 162

if [ -w /sys/kernel/uevent_helper ]; then
	echo > /sys/kernel/uevent_helper
fi

[ -x /sbin/restorecon ] && /sbin/restorecon -R "${VDEV_MOUNTPOINT}" || true

# Coldplug is a oneshot and does not re-run when this service restarts.
# After promote, stay on the long-running profile so eventfs keeps every
# subsystem. First boot has none of these stamps, so it still starts early.
if [ -e "${VDEV_EARLY_STAMP:-/run/vdev/vdev.ready}" ] \
	|| [ -e /run/vdev/vdev-promote ] \
	|| [ -e "${VDEV_TERMINAL_STAMP:-/run/vdev/vdevd-1-coldplug.ready}" ]; then
	exec "${VDEV_BIN}" -f -c "${VDEV_CONFIG_DIR}/${VDEV_LONG_RUNNING}" "${VDEV_MOUNTPOINT}"
fi

exec "${VDEV_BIN}" -f -c "${VDEV_CONFIG_DIR}/${VDEV_EARLY}" "${VDEV_MOUNTPOINT}"
