#!/bin/sh
#
# bluetooth    Bluetooth subsystem starting and stopping
#
# chkconfig: 345 35 90
# description: Bluetooth subsystem
#

# Source function library.
. /etc/rc.d/init.d/functions

PATH=/sbin:/bin:/usr/sbin:/usr/bin
NAME=bluetooth
DESC="Bluetooth subsystem"

HCID_NAME=hcid
HIDD_NAME=hidd
HID2HCI_NAME=hid2hci
RFCOMM_NAME=rfcomm
PAND_NAME=pand
DUND_NAME=dund

HCID_EXEC="`which $HCID_NAME || true`"
HIDD_EXEC="`which $HIDD_NAME || true`"
HID2HCI_EXEC="`which $HID2HCI_NAME || true`"
RFCOMM_EXEC="`which $RFCOMM_NAME || true`"
PAND_EXEC="`which $PAND_NAME || true`"
DUND_EXEC="`which $DUND_NAME || true`"

HCID_ENABLE=true
HIDD_ENABLE=false
HID2HCI_ENABLE=false
RFCOMM_ENABLE=true
DUND_ENABLE=false
PAND_ENABLE=false

HCID_CONFIG="/etc/bluetooth/hcid.conf"
RFCOMM_CONFIG="/etc/bluetooth/rfcomm.conf"

HIDD_OPTIONS=""
DUND_OPTIONS=""
PAND_OPTIONS=""

[ -e /etc/sysconfig/bluetooth ] && . /etc/sysconfig/bluetooth

LOCKFILE=/var/lock/subsys/bluetooth
RETVAL=0

start()
{
	echo "Starting $DESC:"
	if $HCID_ENABLE && [ -x "$HCID_EXEC" -a -f "$HCID_CONFIG" ] ; then
		start_daemon --lockfile "$LOCKFILE" $HCID_EXEC -s -f $HCID_CONFIG
	fi
	RETVAL=$?
	if $HIDD_ENABLE && [ -x "$HIDD_EXEC" ] ; then
		start_daemon $HIDD_EXEC $HIDD_OPTIONS --server || true
	fi
	if $HID2HCI_ENABLE && [ -x "$HID2HCI_EXEC" ] ; then
		start_daemon $HID2HCI_EXEC --tohci > /dev/null 2>&1 || true
	fi
	if $RFCOMM_ENABLE && [ -x "$RFCOMM_EXEC" -a -f "$RFCOMM_CONFIG" ] ; then
		start_daemon $RFCOMM_EXEC -f $RFCOMM_CONFIG bind all || true
	fi
	if $DUND_ENABLE && [ -x "$DUND_EXEC" -a -n "$DUND_OPTIONS" ] ; then
		start_daemon $DUND_EXEC $DUND_OPTIONS
	fi
	if $PAND_ENABLE && [ -x "$PAND_EXEC" -a -n "$PAND_OPTIONS" ] ; then
		start_daemon $PAND_EXEC $PAND_OPTIONS
	fi
	echo
}

stop()
{
	echo "Stopping $DESC:"
	if $PAND_ENABLE && [ -x "$PAND_EXEC" -a -n "$PAND_OPTIONS" ] ; then
		killall $PAND_NAME > /dev/null 2>&1 || true
		echo -n " $PAND_NAME"
	fi
	if $DUND_ENABLE && [ -x "$DUND_EXEC" -a -n "$DUND_OPTIONS" ] ; then
		killall $DUND_NAME > /dev/null 2>&1 || true
		echo -n " $DUND_NAME"
	fi
	start_daemon $RFCOMM_EXEC release all
	if $HIDD_ENABLE && [ -x "$HIDD_EXEC" ] ; then
		killall $HIDD_NAME > /dev/null 2>&1 || true
	fi
	if $HCID_ENABLE && [ -x "$HCID_EXEC" -a -f "$HCID_CONFIG" ] ; then
		stop_daemon --lockfile "$LOCKFILE" $HCID_NAME
	fi
	RETVAL=$?
	echo
}

restart()
{
	echo -n "Restart $DESC: "
	stop
	start
	echo
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
        reload|restart)
		restart
                ;;
        condstop)
	        if [ -e "$LOCKFILE" ]; then
		        stop
		fi
		;;
	condrestart)
		if [ -e "$LOCKFILE" ]; then
		        restart
		fi
		;;
	status)
		status "$HCID_EXEC"
		;;
	*)
		echo "Usage: ${0##*/} {start|stop|reload|restart|condstop|condrestart|status}"
		RETVAL=1
		;;
esac

exit $RETVAL
