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

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

# Source Bluetooth configuration.
#. /etc/sysconfig/bluetooth

prog="Bluetooth"
HARDWARE=`cat /proc/cpuinfo | grep 'Hardware' | cut -d':' -f2 | cut -d' ' -f3`
if [ "$HARDWARE" = "Borzoi" ] || [ "$HARDWARE" = "Terrier" ] || [ "$HARDWARE" = "Spitz" ]; then
  SOCKET=1
else
  SOCKET=0
fi

if [ "`pccardctl status|grep unbound`" != "" ]; then 
  pccardctl eject $SOCKET 2>/dev/null
  pccardctl insert $SOCKET 2>/dev/null
fi
 
UART_CONF="/etc/bluetooth/uart.conf"
if [ -f /etc/bluetooth/bt-uart.conf ]; then
	UART_CONF="/etc/bluetooth/bt-uart.conf"
fi

start_uarts()
{
	[ -f /sbin/hciattach -a -f $UART_CONF ] || return
	grep -v '^#' $UART_CONF | while read i; do
		/sbin/hciattach $i 2>/dev/null
	done
}

stop_uarts()
{
	killproc hciattach > /dev/null 2>&1
}

start() 
{
        echo -n $"Starting $prog: "
	#if [ ! -r /dev/.devfsd ]; then
	    /etc/rc.d/init.d/create_dev
	#fi
        daemon /sbin/hcid

	if [ -x /usr/sbin/sdpd ]; then
		daemon /usr/sbin/sdpd
	fi

	if [ -x /bin/rfcomm -a -f /etc/bluetooth/rfcomm.conf ]; then
		/bin/rfcomm -f /etc/bluetooth/rfcomm.conf bind all 2>/dev/null
	fi

	start_uarts
	touch /var/lock/subsys/bluetooth
        echo
}

stop() 
{
        echo -n $"Shutting down $prog: "
	killproc hcid

	if [ -x /usr/sbin/sdpd ]; then
		killproc sdpd
	fi

	if [ -x /bin/rfcomm ]; then
		/bin/rfcomm release all
	fi

	stop_uarts
	rm -f  /var/lock/subsys/bluetooth
        echo
}

[ -f /sbin/hcid ] || exit 0

# See how we were called.
case "$1" in
  start)
        if [ "`pccardctl ident|grep serial`" != "" ]; then
	  /etc/pcmcia/bluetooth start
        else
	  start
        fi
        ;;
  stop)
        if [ "`pccardctl ident|grep serial`" != "" ]; then
	  /etc/pcmcia/bluetooth stop
        else
	  stop
        fi
        ;;
  restart|reload)
	stop
	start
	;;
  condrestart)
	[ -e /var/lock/subsys/bluetooth ] && (stop; start)
	;;
  *)
        echo $"Usage: $0 {start|stop|restart|reload|condrestart}"
        exit 1
esac

exit 0
