#! /bin/sh
#
# bluez-utils    Bluetooth subsystem starting and stopping
#
# Edd Dumbill <edd@usefulinc.com>

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DESC=bluez-utils

HCID=/sbin/hcid
HCIATTACH=/sbin/hciattach
HCID_NAME=hcid

UART_CONF=/etc/bluetooth/uart

RFCOMM=/bin/rfcomm
RFCOMM_NAME=rfcomm
RFCOMM_CONF=/etc/bluetooth/rfcomm.conf

test -x $HCID || exit 0
test -x $HCIATTACH || exit 0
test -x $RFCOMM || exit 0

set -e

start_uarts()
{
	[ -f $HCIATTACH -a -f $UART_CONF ] || return
	grep -v '^#' $UART_CONF | while read i; do
		$HCIATTACH $i
	done
}

stop_uarts()
{
	killall hciattach > /dev/null 2>&1 || true
}

start_rfcomm()
{
	if [ -x $RFCOMM -a -f $RFCOMM_CONF ] ; then
		# rfcomm must always succeed for now: users
		# may not yet have an rfcomm-enabled kernel
		$RFCOMM -f $RFCOMM_CONF bind all || true
		echo -n " $RFCOMM_NAME"
	fi
}

stop_rfcomm()
{
	if [ -x $RFCOMM ] ; then
		echo -n " $RFCOMM_NAME"
		$RFCOMM unbind all || true
	fi
}

restart_rfcomm()
{
	if [ -x $RFCOMM -a -f $RFCOMM_CONF ] ; then
		$RFCOMM unbind all || true
		$RFCOMM -f $RFCOMM_CONF bind all || true
		echo -n " $RFCOMM_NAME"
	fi
}


case "$1" in
  start)
	echo -n "Starting $DESC:"
	start-stop-daemon --start --quiet --exec $HCID || true
	echo -n " $HCID_NAME"
	start_uarts || true
	start_rfcomm || true
	echo "."
	;;
  stop)
	echo -n "Stopping $DESC:"
	stop_rfcomm
	start-stop-daemon --stop --quiet --exec $HCID || true
	echo -n " $HCID_NAME"
	stop_uarts
	echo "."
	;;
  restart|force-reload)
	echo -n "Restarting $DESC:"
	start-stop-daemon --stop --quiet --exec $HCID || true
	sleep 1
	start-stop-daemon --start --quiet --exec $HCID || true
	echo -n " $HCID_NAME"
	restart_rfcomm
	echo "."
	;;
  *)
	N=/etc/init.d/bluez-utils
	# echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
	echo "Usage: $N {start|stop|restart|force-reload}" >&2
	exit 1
	;;
esac

exit 0
