#!/bin/bash

PROGRAM=/usr/bin/dbus-daemon
ARGS="--system"
RUNLEVEL=3
NEEDS="devices"
PIDFILE=/run/dbus/pid

. /etc/init.d/smgl_init

start() {
  echo  "Starting system message bus..."
  mkdir -p $(dirname $PIDFILE)
  # make sure there is actually a process there...
  if [ -f $PIDFILE ]; then
    echo "Found $PIDFILE doing extra checks..."
    local pid=$(cat "$PIDFILE")
    if ! grep -q "^$PROGRAM" /proc/"$pid"/cmdline; then
      print_status warning "$PIDFILE exists, but messagebus is not running under this PID"
      echo "Attempting cleanup and new startup..."
      rm -f $PIDFILE
    else
      echo "Seems to be running..."
      return 0
    fi
  fi
  # don't use loadproc here, as that fails if some user is running
  # a session bus
  $PROGRAM $ARGS
  evaluate_retval
  echo "Creating dbus machine uuid..."
  /usr/bin/dbus-uuidgen --ensure
  evaluate_retval
}

stop() {
  if [ ! -f $PIDFILE ]; then
    echo "System message bus is not running"
    return 0
  fi
  echo  "Stopping system message bus..."
  kill  $(cat $PIDFILE)
  if [ $? -eq 0 ]; then
    rm -f $PIDFILE
  fi
  evaluate_retval
}

restart() {
  echo "Restarting system message bus..."
  if [ -f $PIDFILE ]; then
    $0 stop
    sleep 2
  fi
  $0 start
}

status() {
  if [ ! -f $PIDFILE ]; then
    echo "System message bus is not running"
    return 0
  fi
  local pid=$(cat $PIDFILE)
  if ps -p $pid > /dev/null; then
    echo  "System message bus is running with Process ID $pid"
  else
    echo  "System message bus is not running, but $PIDFILE exists"
    return 1
  fi
}

reload() {
  echo "Reloading D-BUS configuration..."
  /usr/bin/dbus-send --print-reply \
                     --system \
                     --type=method_call \
                     --dest=org.freedesktop.DBus \
                     / org.freedesktop.DBus.ReloadConfig > /dev/null

  evaluate_retval
}

usage() {
  echo "Usage: $0 {start|stop|restart|reload|status}"
}
