description	"System message bus"
author		"Michael Biebl"

start on ACT_DEAD
stop on USER
stop on starting shutdown

console none

pre-start script
	DAEMON=/usr/bin/dbus-daemon
	UUIDGEN=/usr/bin/dbus-uuidgen
	UUIDGEN_OPTS=--ensure
	DAEMONUSER=messagebus
	PIDDIR=/var/run/dbus
	PIDFILE=$PIDDIR/pid
	MACHINE_ID=/var/lib/dbus/machine-id

	. /lib/lsb/init-functions

	create_machineid() {
	  # Create machine-id file if it does not exist (this is the first boot) or
	  # empty (due to an unclean reboot).
	  if [ ! -f $MACHINE_ID -o ! -s $MACHINE_ID ]; then
	    # machine-id file does not exist or is empty
	    if [ -x $UUIDGEN ]; then
	      if [ -f $MACHINE_ID ]; then
	        # machine-id file is empty, remove it to make dbus-uuidgen happy
	        rm $MACHINE_ID
	      fi
	      # generate machine-id file
	      $UUIDGEN $UUIDGEN_OPTS
	    else
	      log_warning_msg "The machine-id file cannot be created."
	    fi
	  fi
	}

	# PID dir is made also in dsmetool case, so that system.conf
	# does not need changes
	if [ ! -d $PIDDIR ]; then
	  mkdir -p $PIDDIR
	  chown $DAEMONUSER:$DAEMONUSER $PIDDIR
	fi

	if [ -e $PIDFILE ]; then
	  PIDDIR=/proc/$(cat $PIDFILE)
	  if ! [ -d ${PIDDIR} -a  "$(readlink -f ${PIDDIR}/exe)" = "${DAEMON}" ]; then 
	    log_success_msg "Removing stale PID file $PIDFILE."
	    rm -f $PIDFILE
	  fi
	fi

	create_machineid

	echo "Starting dbus"
end script

post-start script
	# Block until the daemon is ready for use
	while [ ! -e /var/run/dbus/system_bus_socket ]; do
		sleep 1
	done
end script

exec /usr/bin/dbus-daemon --system --nofork
respawn

