#!/bin/sh
# chkconfig: 2345 23 77
### BEGIN INIT INFO
# Provides:          hal
# Required-Start:    modules $local_fs
# Required-Stop:     
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start hal at boot time
# Description:       Enable service provided by hal.
# X-Start-Before:    
# X-Stop-After:      
# X-Timesys-Start-Number:  23
# X-Timesys-Stop-Number:  77
### END INIT INFO

set -e

PATH=/usr/bin:/bin:/usr/sbin:/sbin
DAEMON=hald
PID_FILE=/var/run/hald/pid
DESC="Hardware Abstraction Layer daemon"
#OPTS=--use-syslog

case "$1" in
    start)
        if ! grep ^haldaemon /etc/passwd > /dev/null; then
            echo "$0: Creating system user 'haldaemon' with generic settings.  Review and modify as required."
            yes '' | adduser haldaemon >/dev/null 2>&1 || yes '' | useradd haldaemon >/dev/null 2>&1
        fi
        if [ -e $PID_FILE ]; then
            PIDDIR=/proc/$(cat $PID_FILE)
            if [ -d ${PIDDIR} -a -n "$(readlink -f ${PIDDIR}/exe 2>/dev/null)" ]; then
                echo "$DESC already started; not starting."
                return
            else
                echo "Removing stale PID file $PID_FILE."
                rm -f $PID_FILE
            fi
        fi
        echo -n "Starting $DESC: "
        $DAEMON ${OPTS} && \
          echo '[ OK ]' || echo '[FAIL]'
    ;;
    stop)
        if [ -f $PID_FILE ]; then
            echo -n "Stopping $DESC: "
            read PID < $PID_FILE
            kill $PID && \
              echo '[ OK ]' || echo '[FAIL]'
            rm $PID_FILE
        else
            echo "pid file not found... is $DAEMON running?"
        fi
    ;;
    restart)
      $0 stop
      $0 start
    ;;
    *)
        echo "usage: $0 {start|stop|restart}"
        exit 1
    ;;
esac
