#! /bin/sh
#
# moblin-system-daemon:   Moblin Settings primary daemon
#
# chkconfig: - 99 21
# description:  This script kicks off the settings daemon.
#
# processname: moblin-system-daemon
#
### BEGIN INIT INFO
# Provides: moblin-system-daemon
# Required-Start: messagebus haldaemon
# Required-Stop: messagebus
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Start/Stop the settings daemon
# Description: Start/Stop the settings daemon
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/moblin-system-daemon
NAME=moblin-system-daemon
DESC="MoblinSystemDaemon"
PROCESSES=`ps xo pid,args | grep /usr/sbin/$NAME | grep -v grep | grep -v invoke-rc | tr ' ' '\n' | sed -n -e "/[0-9]/p" | tr '\n' ' '`
ALLPROCESSES=`ps axo pid,args | grep /usr/sbin/$NAME | grep -v grep | grep -v invoke-rc | tr ' ' '\n' | sed -n -e "/[0-9]/p" | tr '\n' ' '`

. /lib/lsb/init-functions

test -x $DAEMON || exit 0

set -e

get_pids() {
	PROCESSES=`ps xo pid,args | grep /usr/sbin/$NAME | grep -v grep | grep -v invoke-rc | tr ' ' '\n' | sed -n -e "/[0-9]/p" | tr '\n' ' '`
	ALLPROCESSES=`ps axo pid,args | grep /usr/sbin/$NAME | grep -v grep | grep -v invoke-rc | tr ' ' '\n' | sed -n -e "/[0-9]/p" | tr '\n' ' '`
}

do_start() {
	if [ -z "$PROCESSES" ]; then
		echo -n $"Starting $DESC... "
		$DAEMON
		echo $"DONE"
	else
		echo $"$DESC is already running"
	fi
}

do_stop() {
	for i in $ALLPROCESSES; do
		echo -n $"Stopping $DESC (PID=$i)... "
		kill $i
		echo $"DONE"
	done
}

case "$1" in
  start)
	if [ ! -e /var/run/dbus/system_bus_socket ]; then
		log_failure_msg "Can't start $DESC - please ensure dbus is running"
		exit 0
	fi
	
	do_start
	;;
  stop)
	do_stop
	;;
  restart|force-reload)
	do_stop
	get_pids
	sleep 1
	do_start
	;;
  *)
	log_success_msg "Usage: $0 {start|stop|restart|force-reload}" >&2
	exit 1
	;;
esac

exit 0
