#!/bin/sh
########################################################################
# Begin bluetooth
#
# Description : BlueZ Boot Script
#
# Authors     : Armin K. <krejzi@email.com>
#
# Version     : BLFS SVN
#
# Notes       : Configurable through /etc/sysconfig/bluetooth
#             : Rewritten May 29, 2014 for bluez-5 by 
#               Bruce Dubbs <bdubbs@linuxfromscratch.org>
#
########################################################################

### BEGIN INIT INFO
# Provides:            bluetooth
# Required-Start:      $local_fs $syslog dbus
# Required-Stop:       $local_fs $syslog
# Default-Start:       2 3 4 5
# Default-Stop:        0 1 6
# Short-Description:   Starts bluetooth daemons
# X-LFS-Provided-By:   BLFS
### END INIT INFO

. /lib/lsb/init-functions

if [ -f "/etc/sysconfig/bluetooth" ]; then
   . /etc/sysconfig/bluetooth
fi

BLUETOOTH=/usr/sbin/bluetoothd
SDPTOOL=/usr/bin/sdptool
HCIATTACH=/usr/bin/hciattach
RFCOMM=/usr/bin/rfcomm

UART_CONF=/etc/bluetooth/uart.conf
RFCOMM_CONF=/etc/bluetooth/rfcomm.conf

start_hci_dev()
{
   for dev in ${ACTIVE_HCI_DEVICES_ON_BOOT} ; do
      hciconfig $dev up > /dev/null 2>&1 
   done
}

run_sdptool()
{
   # Declaring IFS local in this function, removes the need to
   # save/restore it
   local IFS option

   test -x $SDPTOOL || return 1

   IFS=";"
   for option in ${SDPTOOL_OPTIONS}; do
      IFS=" "
      $SDPTOOL $option > /dev/null 2>&1
   done
}

start_uarts()
{
   [ -x $HCIATTACH ] && [ -f $UART_CONF ] || return

   grep -v '^[[:space:]]*(#|$)' $UART_CONF | while read i; do
      $HCIATTACH $i > /dev/null 2>&1
   done
}

stop_uarts()
{
   [ -x $HCIATTACH ] || return
   killall $HCIATTACH > /dev/null 2>&1 
}

start_rfcomm()
{
   [ -x $RFCOMM ] && [ -f $RFCOMM_CONF ]  || return 

   $RFCOMM -f $RFCOMM_CONF bind all > /dev/null 2>&1 || :
}

stop_rfcomm()
{
   [ -x $RFCOMM ] || return
   $RFCOMM unbind all > /dev/null 2>&1 
}

case "${1}" in
   start)
      log_info_msg "Starting Bluetooth daemon bluetoothd..."
      pidlist=`pidofproc $BLUETOOTH`

      if [  "${?}" = "0" ]; then
        log_info_msg2 " Already running"
        log_success_msg2
        exit 0;
      fi

      # Start as background process and assume OK
      $BLUETOOTH &
      log_success_msg2

      start_hci_dev
      run_sdptool
      start_uarts
      start_rfcomm
      ;;

   stop)
      stop_rfcomm
      stop_uarts

      log_info_msg "Stopping Bluetooth daemon bluetoothd..."
      killproc $BLUETOOTH
      evaluate_retval
      ;;

   restart)
      ${0} stop
      sleep 1
      ${0} start
      ;;

   status)
      statusproc $BLUETOOTH
      ;;

   *)
      echo "Usage: ${0} {start|stop|restart|status}"
      exit 1
      ;;
esac

exit 0

# End bluetooth
