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

start_uarts()
{
    [ -f /usr/sbin/hciattach -a -f $UART_CONF ] || return
        ID=`/sbin/cardctl ident $SOCKET | grep info: | sed 's/^ *product info: *//' | sed 's/"/\\"/g'`
        UART_SET=`grep "$ID" $UART_CONF | cut -f2 -d":"`
#        if [ "$UART_SET" != "" ]; then
#      /usr/sbin/hciattach $UART_SET
#          /etc/pcmcia/serial start
#   fi
}

stop_uarts()
{
    killproc hciattach > /dev/null 2>&1
#   /etc/pcmcia/serial stop
}

start() 
{

    [ -f /var/lock/subsys/bluetooth.starting ] && exit 0

    echo -n $"Starting $prog... "
    
    
    touch /var/lock/subsys/bluetooth.starting
    
    modprobe rfcomm
    modprobe l2cap

    /usr/bin/make_dev.bluez.sh
        
    daemon /usr/sbin/hcid

    if [ -x /usr/sbin/sdpd ]; then
        daemon /usr/sbin/sdpd
    fi
    
    modprobe hidp
    if [ -x /usr/bin/hidd ]; then
        daemon /usr/bin/hidd --server
    fi

#   start_uarts
    /usr/bin/rfcomm bind all
    
    if [ -x /usr/sbin/opd ]; then
    
        OBEX_INBOX=/home/zaurus/Documents/Obex_Inbox
	
        if [ ! -d $OBEX_INBOX ]; then
	    mkdir $OBEX_INBOX
	    chown zaurus:qpe $OBEX_INBOX
	fi
	/usr/sbin/opd --mode OBEX+BIP --path  $OBEX_INBOX --channel 4 --sdp --daemonize
    fi

    rm -f /var/lock/subsys/bluetooth.starting

    touch /var/lock/subsys/bluetooth
    echo "Done."
}

stop() 
{
    echo -n $"Shutting down $prog... "

    if [ -x /usr/sbin/opd ]; then
        killproc opd
    fi
    
    hciconfig hci0 down
    sleep 1
    
    /usr/bin/rfcomm release all
    killproc hcid

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

    if [ -x /usr/bin/hidd ]; then
        killproc hidd
    fi

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

    rm -f  /var/lock/subsys/bluetooth
    echo "Done."
}

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

# configuration via USB hotplug
if [ "$ACTION"x != ""x ]; then
case "$ACTION" in
  register)
    start
        ;;
  unregister)
    stop
        ;;
  *)
    mesg "$ACTION unhandled"
    exit 0
esac
fi

# 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
