#! /bin/bash
#
# messagebus   Start/Stop the DBus system bus
# v1.0 2018-03-04 Yaakov Selkowitz
#
# chkconfig: 2345 90 60
# description: DBus system bus
# processname: dbus-daemon
# config: /etc/dbus-1/system.conf
# pidfile: /var/run/dbus/pid

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
PREFIX=/usr
CONFIG=/etc/dbus-1/system.conf
PIDFILE=/var/run/dbus/pid
LOGFILE=/var/log/dbus-daemon.log
SOCKET=/var/run/dbus/system_bus_socket

# Source function library.
if [ -f /etc/init.d/functions ] ; then
  . /etc/init.d/functions
fi

RETVAL=0

# See how we were called.

prog="messagebus"
progdir="/usr/bin"
DAEMON="$progdir/dbus-daemon.exe"

test -f $DAEMON || exit 0

# Source configuration
if [ -f /etc/sysconfig/$prog ] ; then
    . /etc/sysconfig/$prog
fi

start() {
        echo -n $"Starting $prog: "
        # check if cygrunsrv process
        cygrunsrv --start $prog
        RETVAL=$?
        [ $RETVAL -eq 0 ] && touch $PIDFILE  && echo "done."
        return $RETVAL
}

stop() {
        echo -n $"Stopping $prog: "
        cygrunsrv --stop $prog
        if test -r $PIDFILE; then
            kill `cat $PIDFILE` 2> /dev/null || echo "failed."
        fi
        # this really needs a long time to stop.
        RETVAL=$?
        [ $RETVAL -eq 0 ] && rm -f $PIDFILE $SOCKET && echo "done."
        return $RETVAL
}

rhstatus() {
        # service status
        cygrunsrv -Q $prog
}

restart() {
        echo $"Restarting $prog: "
        $0 stop
        sleep 1
        $0 start
        echo "done."
}

install() {
        echo -n $"Installing $prog daemon: "
        # some safety measures
        touch $LOGFILE $PIDFILE
        chgrp 18 $LOGFILE $PIDFILE
        chmod g+w $LOGFILE $PIDFILE
        rm -f $SOCKET
        #it was compiled with uid=18
        cygrunsrv --install $prog --path $DAEMON --args "--nofork --system" --disp "CYGWIN D-Bus system service"
        echo "done."
}
uninstall() {
        echo -n $"Uninstalling $prog daemon: "
        stop
        cygrunsrv --remove $prog
        echo "done."
}
reload() {
        echo -n $"Reloading $prog daemon configuration: "
        /usr/bin/kill -HUP `cat $PIDFILE`
        RETVAL=$?
        [ $RETVAL -eq 0 ] && echo "done."
        RETVAL=$?
        return $RETVAL
}

case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  restart)
        restart
        ;;
  reload)
        reload
        ;;
  install)
        install
        ;;
  uninstall)
        uninstall
        ;;
  status)
        rhstatus
        ;;
  condrestart)
        [ -f $PIDFILE ] && restart || :
        ;;
  *)
        echo $"Usage: $0 {start|stop|status|install|uninstall|restart|condrestart}"
        exit 1
esac

exit $?
