#! /bin/sh
#
# pmud	       Power Manager daemon for Apple powerbooks
#
# chkconfig: 2345 40 60
# description: pmud is a daemon which periodically polls the PMU \
#              (power manager) and performs functions such as enabling \
#              or disabling devices appropriately when the power source \
#              changes.
# processname: pmud
# config: /etc/power/levels
# pidfile: /var/run/pmud.pid

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/sbin/pmud
NAME=pmud
PIDFILE=/var/run/$NAME.pid
DESC="Power Management Unit"

status() {
        # Test syntax.
        if [ $# = 0 ] ; then
                echo "Usage: status {program}"
                return 1
        fi

        # First try "pidof"
        pid=`pidof $1`
        if [ "$pid" != "" ] ; then
                echo "$1 (pid $pid) is running..."
                return 0
        else
                pid=`ps ax | awk 'BEGIN { prog=ARGV[1]; ARGC=1 } 
                           { if ((prog == $5) || (("(" prog ")") == $5) ||
                             (("[" prog "]") == $5) ||
                           ((prog ":") == $5)) { print $1 ; exit 0 } }' $1`
                if [ "$pid" != "" ] ; then
                        echo "$1 (pid $pid) is running..."
                        return 0
                fi
        fi

        # Next try "/var/run/*.pid" files
        if [ -f /var/run/$1.pid ] ; then
                pid=`head -1 /var/run/$1.pid`
                if [ "$pid" != "" ] ; then
                        echo "$1 dead but pid file exists"
                        return 1
                fi
        fi
        echo "$1 not running"
        return 2
}

# Source power daemon options
[ -f /etc/default/power ] && . /etc/default/power

test -f $DAEMON || exit 0

# See how we were called.
case "$1" in
  start)
	echo -n "Starting $NAME: "
	start-stop-daemon --start --quiet --make-pidfile --pidfile $PIDFILE --exec $DAEMON -- $PMUD_FLAGS
	#echo "$NAME."
	;;
  stop)
	echo -n "Stopping $NAME: "
	start-stop-daemon --stop --quiet --exec $DAEMON
	[ -f $PIDFILE ] && rm -f $PIDFILE
	echo "$NAME."
	;;
  restart|force-reload)
	$0 stop
	sleep 1
	$0 start
	;;
  status)
	status pmud
	;;
  *)
	echo "Usage: pmud {start|stop|status}"
	exit 1
esac

exit 0
