#!/bin/sh
#Copyright: 2022-2023 Lorenzo Puliti <plorenzo@disroot.org>
#           2026 Aitor <aitor@genuen.org>
#License: CC0-1.0

# Plain sh: avoid invoke-run so early-boot failures are visible in the log.
exec 2>&1

mkdir -p /run/dbus
if getent passwd messagebus >/dev/null 2>&1; then
	chown messagebus:messagebus /run/dbus 2>/dev/null || true
fi
# Stale socket/pid from a crashed instance prevents bind().
rm -f /run/dbus/system_bus_socket /run/dbus/pid

# /var/run is usually a symlink to /run; keep a dir if it is not.
if [ -d /var/run ] && [ ! -L /var/run ]; then
	mkdir -p /var/run/dbus
	if getent passwd messagebus >/dev/null 2>&1; then
		chown messagebus:messagebus /var/run/dbus 2>/dev/null || true
	fi
	rm -f /var/run/dbus/system_bus_socket /var/run/dbus/pid
fi

if ! mountpoint -q /proc; then
	echo "dbus: /proc is not mounted" >&2
	exit 162
fi

if [ -x /usr/bin/dbus-uuidgen ]; then
	/usr/bin/dbus-uuidgen --ensure 2>/dev/null || true
fi

DBUS_BIN=##bin##
if [ ! -x "$DBUS_BIN" ]; then
	DBUS_BIN=/usr/bin/dbus-daemon
fi
if [ ! -x "$DBUS_BIN" ]; then
	echo "dbus: dbus-daemon not installed" >&2
	exit 162
fi

# Foreground under runsv; no pidfile (we cleared any stale one above).
exec "$DBUS_BIN" --system --nofork --nopidfile
