#! /bin/sh
# based on MCE init.d script

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/powered
NAME=powered
DESC="Power Event Daemon"
DAEMON_OPTS=
DSMETOOL=/usr/sbin/dsmetool
PIDFILE=/var/run/$NAME.pid
INITFILE=/etc/init.d/$NAME
WAITDBUS=/usr/bin/waitdbus
WAITDBUS_ALT=/usr/sbin/waitdbus

# abort if no executable exists
test -x $DAEMON || exit 0

# only use dsmetool if it exists
test -x $DSMETOOL || USE_DSMETOOL=no

START_POWERED=true
MCE_STOP=true
MCE_START=true

if [ -r /etc/default/powered ]; then
    . /etc/default/powered
fi

start_powered()
{
if [ -x $WAITDBUS ]; then
	$WAITDBUS system
elif [ -x $WAITDBUS_ALT ]; then
	$WAITDBUS_ALT system
fi

if [ x"$USE_DSMETOOL" = x"no" ]; then
	daemon --name=powered --pidfiles=/var/run --pidfile=$PIDFILE $DAEMON
else
	$DSMETOOL -n -1 -t "$DAEMON $NORMAL_OPTS"
fi
}

stop_powered()
{
if [ x"$USE_DSMETOOL" = x"no" ]; then
	killall $DAEMON
	sleep 2
	killall -9 $DAEMON
else
	$DSMETOOL -n -1 -k "$DAEMON $NORMAL_OPTS"
fi
}

case "$1" in
start)
    if [ "$START_POWERED" != "true" ]; then
          echo "Not starting powered: disabled by /etc/default/powered."
          exit 0
    fi
    if [ "$MCE_STOP" = "true" ]; then
      if pidof mce > /dev/null; then
          printf "mce is running...stopping\n"
          if [ -x "`which invoke-rc.d 2>/dev/null`" ]; then
              invoke-rc.d mce stop || exit $?
          else
             /etc/init.d/mce stop || exit $?
          fi
      fi
    fi

	printf "Starting $DESC: $NAME"
	start_powered
	printf ".\n"
	;;

stop)
	printf "Stopping: $DESC: $NAME"
	stop_powered
	printf ".\n"

    if [ "$MCE_START" = "true" ]; then
      if ! pidof mce > /dev/null; then
        if [ -x "`which invoke-rc.d 2>/dev/null`" ]; then
            invoke-rc.d mce start || exit $?
        else
            /etc/init.d/mce start || exit $?
        fi
      fi
    fi
	;;

restart|force-reload)
	printf "Restarting $DESC: $NAME"
	stop_powered
	sleep 2
	start_powered
	printf ".\n"
	;;

*)
	printf "Usage: $INITFILE {start|stop|restart|force-reload}\n" >&2
	exit 1
	;;
esac

exit 0
