#!/usr/sbin/openrc-run

description="D-Bus systemwide message bus"

DAEMON=/usr/bin/dbus-daemon
UUIDGEN=/usr/bin/dbus-uuidgen
UUIDGEN_OPTS=--ensure
DAEMONUSER=messagebus
PIDDIR=/var/run/dbus
PIDFILE=${PIDDIR}/pid
MACHINEID=/var/lib/dbus/machine-id
GRACETIME=60

command="${DAEMON}"
command_args="--system ${PARAMS:-}"

extra_started_commands="reload force-reload"

depend() {
	need localmount
	use logger
	after rsyslog bootmisc
}

create_machineid() {
	local UPTIME

	UPTIME=$(cut -d " " -f 1 /proc/uptime | sed 's/\..*//g')
	if [ "${IDTYPE:-}" = "RANDOM" ] && \
		[ -f "${MACHINEID}" ] && \
		[ ! -d "$PIDDIR" -o "${UPTIME}" -lt "${GRACETIME}" ]; then
		rm -f "${MACHINEID}"
	fi
	if [ -x "$UUIDGEN" ]; then
		"$UUIDGEN" $UUIDGEN_OPTS
	fi
}

prepare() {
	[ -x "$command" ] || return 1
	[ -e /etc/default/dbus ] && . /etc/default/dbus
	command_args="--system ${PARAMS:-}"

	create_machineid
	if [ ! -d "$PIDDIR" ]; then
		mkdir -p "$PIDDIR"
		chown "$DAEMONUSER" "$PIDDIR"
		chgrp "$DAEMONUSER" "$PIDDIR"
	fi

	if ! mountpoint -q /proc/; then
		eerror "Can't start ${description} - /proc is not mounted"
		return 1
	fi

	export SYSTEMD_NSS_BYPASS_BUS=1
	return 0
}

start() {
	if ! prepare; then
		return 1
	fi
	if [ -e "$PIDFILE" ] && start-stop-daemon -K -t -p "$PIDFILE" >/dev/null 2>&1; then
		einfo "${description} already started; not starting."
		return 0
	fi
	[ -e "$PIDFILE" ] && rm -f "$PIDFILE"
	ebegin "Starting ${RC_SVCNAME}"
	start-stop-daemon -S -p "$PIDFILE" \
		-x "$command" -- ${command_args}
	eend $?
}

stop() {
	ebegin "Stopping ${RC_SVCNAME}"
	start-stop-daemon -K -R 5 -p "$PIDFILE" -u "$DAEMONUSER"
	local rc=$?
	rm -f "$PIDFILE"
	eend "$rc"
}

reload() {
	create_machineid
	ebegin "Reloading ${description} config"
	dbus-send --print-reply --system --type=method_call \
		--dest=org.freedesktop.DBus \
		/ org.freedesktop.DBus.ReloadConfig > /dev/null
	eend $?
}

# SysV/LSB compatibility: packages (e.g. rtkit) call
# invoke-rc.d dbus force-reload after installing D-Bus policy.
force_reload() {
	reload
}
