#! /bin/sh
# -*- coding: utf-8 -*-

set -e

DAEMON=/usr/bin/dbus-daemon
NAME=carmand-dbus
DAEMONUSER=user
PIDDIR=/var/run/dbus
PIDFILE=$PIDDIR/carmand-pid
DESC="carmand message bus"
EVENTDIR=/etc/dbus-1/carmand-dbus.d
CONFFILE=/etc/dbus-1/carmand-dbus.conf

test -x $DAEMON || exit 0

# Source defaults file; edit that file to configure this script.
ENABLED=1
PARAMS="--config-file=$CONFFILE"
if [ -e /etc/default/dbus-1 ]; then
  . /etc/default/dbus-1
fi

test "$ENABLED" != "0" || exit 0

echo `uname -m` | grep "^armv" > /dev/null
if [ $? = 0 -a -x /usr/sbin/dsmetool ]; then
  USE_DT=1
else
  USE_DT=""
fi

start_it_up()
{
 # 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 $PIDDIR
#   chgrp $DAEMONUSER $PIDDIR
 fi
 if [ "x$USE_DT" = "x" ]; then
# # The following is commented because readlink is not available
#  if [ -e $PIDFILE ]; then
#    PIDDIR=/proc/$(cat $PIDFILE)
#    if [ -d ${PIDDIR} -a  "$(readlink -f ${PIDDIR}/exe)" = "${DAEMON}" ]; then 
#      echo "$DESC already started; not starting."
#    else
#      echo "Removing stale PID file $PIDFILE."
#      rm -f $PIDFILE
#    fi
#  fi
  echo -n "Starting $DESC: "
  start-stop-daemon --start --quiet --pidfile $PIDFILE \
    --exec $DAEMON -- $PARAMS --fork
#   --user $DAEMONUSER --exec $DAEMON -- $PARAMS --fork
  echo "$NAME."
 else
  # start with dsmetool
  rm -f $PIDFILE
  echo -n "Starting $DESC: "
  /usr/sbin/dsmetool -r "$DAEMON $PARAMS" -n -5
  echo "$NAME."
 fi
 if [ -d $EVENTDIR ]; then
     run-parts --arg=start $EVENTDIR
 fi
}

shut_it_down()
{
 if [ -d $EVENTDIR ]; then
     run-parts --arg=stop $EVENTDIR
 fi
 if [ "x$USE_DT" = "x" ]; then
  echo -n "Stopping $DESC: "
  start-stop-daemon --stop --retry 60 --quiet --oknodo --pidfile $PIDFILE
   # --user $DAEMONUSER
  # We no longer include these arguments so that start-stop-daemon
  # can do its job even given that we may have been upgraded.
  # We rely on the pidfile being sanely managed
  # --exec $DAEMON -- --system $PARAMS
 else
  # stop with dsmetool
  echo -n "Stopping $DESC: "
  /usr/sbin/dsmetool -k "$DAEMON $PARAMS"
 fi
 echo "$NAME."
 rm -f $PIDFILE
}

case "$1" in
  start)
    start_it_up
  ;;
  stop)
    shut_it_down
  ;;
  restart|force-reload)
    shut_it_down
    sleep 1
    start_it_up
  ;;
  *)
    echo "Usage: /etc/init.d/$NAME {start|stop|restart|force-reload}" >&2
    exit 1
  ;;
esac

exit 0
