#!/usr/bin/env /lib/runit/invoke-run
#Copyright: 2022 Lorenzo Puliti <plorenzo@disroot.org>
#           2026 Aitor <aitor@genuen.org>
#License: CC0-1.0

DEFAULT_DISPLAY_MANAGER=$(cat /etc/X11/default-display-manager 2>/dev/null || true)
# ##bin## → /usr/sbin/lightdm at package build; skip if another DM is default
if [ -n "$DEFAULT_DISPLAY_MANAGER" ] && [ "$DEFAULT_DISPLAY_MANAGER" != "##bin##" ]; then
	exit 161
fi

# Poll the system bus; avoid "sv start dbus" (check scripts can hang).
wait_system_bus() {
	_n=0
	while [ "$_n" -lt 40 ]; do
		if [ -S /run/dbus/system_bus_socket ]; then
			if command -v timeout >/dev/null 2>&1; then
				timeout 1 dbus-send --system --dest=org.freedesktop.DBus \
					--type=method_call /org/freedesktop/DBus \
					org.freedesktop.DBus.Peer.Ping >/dev/null 2>&1 && return 0
			else
				dbus-send --system --dest=org.freedesktop.DBus \
					--type=method_call /org/freedesktop/DBus \
					org.freedesktop.DBus.Peer.Ping >/dev/null 2>&1 && return 0
			fi
		fi
		sleep 0.2
		_n=$((_n + 1))
	done
	return 1
}

wait_system_bus || exit 170
sv up dbus >/dev/null 2>&1 || true
sv up elogind >/dev/null 2>&1 || true
[ -x /usr/sbin/seatd ] && sv up seatd >/dev/null 2>&1 || true

# Socket dirs (also from boot-run x11-common / prepare); cheap if already present
sv once x11-common || true
mkdir -p -m 01777 /tmp/.X11-unix /tmp/.ICE-unix 2>/dev/null || true

if [ -r /etc/default/locale ]; then
	. /etc/default/locale
	export LANG LANGUAGE
fi

if [ -x /bin/plymouth ]; then
	/bin/plymouth quit || true
fi

exec 2>&1

exec ##bin##
