#!/bin/bash
#
# 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"

UART_CONF="/etc/bluetooth/bt-uart.conf"
ID=""
UART_SET=""
SERIAL_SET=""
if [ -f /sbin/hciattach -a -f $UART_CONF ]; then
        ID=`/sbin/cardctl ident | grep info: | sed 's/^ *product info: *//' | sed 's/"/\\"/g'`
        UART_SET=`grep "$ID" $UART_CONF | cut -f2 -d":"`
	SERIAL_SET=`grep "$ID" $UART_CONF | cut -f3 -d":"`
fi

start_uarts()
{
        if [ "$SERIAL_SET" != "" ]; then
          /sbin/setserial $SERIAL_SET
	fi
        if [ "$UART_SET" != "" ]; then
	  modprobe hci_uart > /dev/null 2>&1
          /sbin/hciattach $UART_SET
	  hciconfig hci0 up
	fi
}

stop_uarts()
{
        if [ "$UART_SET" != "" ]; then
	  hciconfig hci0 down
          killproc hciattach > /dev/null 2>&1
	  sleep 1
	  modprobe -r hci_uart > /dev/null 2>&1
	fi
}

start() 
{
    echo -n $"Starting $prog... "
    #modprobe rfcomm > /dev/null 2>&1
    #modprobe l2cap  > /dev/null 2>&1

    start_uarts
    rfcomm release all
    if [ -f /etc/bluetooth/rfcomm.conf ]; then
	/bin/rfcomm -f /etc/bluetooth/rfcomm.conf bind all
    fi
    
    echo "Done."
}

stop() 
{
    echo -n $"Shutting down $prog... "
    
    rfcomm release all
    stop_uarts

    #rmmod rfcomm > /dev/null 2>&1
    #rmmod l2cap >  /dev/null 2>&1
    #rmmod bluez >  /dev/null 2>&1

    echo "Done."
}

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

# See how we were called.
case "$1" in
  start)
    start
        ;;
  stop)
    stop
        ;;
  restart|reload)
    stop
    start
    ;;
  condrestart)
    [ -e /var/lock/subsys/bluetooth ] && (stop; start)
    ;;
  check|suspend|resume|cksum)
        ;;  
  *)
        echo $"Usage: $0 {start|stop|restart|reload|condrestart}"
        exit 1
esac

exit 0
