#! /bin/sh
#
# bluetooth	Bluetooth subsystem starting and stopping
#

NAME=bluetooth
DESC="Bluetooth subsystem"
PATH=/sbin:/bin:/usr/sbin:/usr/bin
DEFAULT=/etc/default/bluetooth
HCID=/usr/sbin/hcid
HCID_CONF=/etc/bluetooth/hcid.conf
HCIATTACH=/usr/sbin/hciattach
UART_CONF=/etc/bluetooth/uart
SDPD=/usr/sbin/sdpd
HIDD=/opt/bluetooth/sbin/bthid
PAND=/usr/bin/pand
DUND=/usr/bin/dund
RFCOMM=/usr/bin/rfcomm
RFCOMM_CONF=/etc/bluetooth/rfcomm.conf

set -e

if [ ! -f "$DEFAULT" ] ; then
	echo "Configuration script "$DEFAULT" does not exist"
	exit 0
fi

start_uarts() 
{
	[ -x "$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
}

case "$1" in
  start)
	echo -n "Starting $DESC:"

	if [ `cat "$DEFAULT" |grep -v '^#' |grep '^HCID' |awk {'print $3'}` = true ] ; then 
		if [ -x "$HCID" -a -f "$HCID_CONF" ] ; then
			"$HCID" -f "$HCID_CONF"
			echo -n " hcid"
		fi
	fi

	if [ `cat "$DEFAULT" |grep -v '^#' |grep '^SDPD' |awk {'print $3'}` = true ] ; then
		if [ -x "$SDPD" ] ; then
			"$SDPD"
			echo -n " sdpd"
		fi
	fi

	if [ `cat "$DEFAULT" |grep -v '^#' |grep '^HIDD' |awk {'print $3'}` = true ] ; then
        	if [ -x "$HIDD" ] ; then
			"$HIDD" -d
			echo -n " hidd"
		fi
	fi

	if [ `cat "$DEFAULT" |grep -v '^#' |grep '^RFCOMM' |awk {'print $3'}` = true ] ; then
		if [ -x "$RFCOMM" -a -f "$RFCOMM_CONF" ] ; then
			"$RFCOMM" -f "$RFCOMM_CONF" bind all
			echo -n " rfcomm"
		fi
	fi

	if [ `cat "$DEFAULT" |grep -v '^#' |grep '^PAND' |awk {'print $3'}` = true ] ; then
		"$PAND" -s -M -r NAP
		echo -n " pand"
		
	fi

	if [ `cat "$DEFAULT" |grep -v '^#' |grep '^CLIENT_PAND' |awk {'print $3'}` = true ] ; then
		echo -n " pand_client"
	fi

	if [ `cat "$DEFAULT" |grep -v '^#' |grep '^DUND' |awk {'print $3'}` = true ] ; then
		echo -n " dund"
	fi

	if [ `cat "$DEFAULT" |grep -v '^#' |grep '^CLIENT_DUND' |awk {'print $3'}` = true ] ; then
		echo -n " dund_client"
	fi

	echo "."
	start_uarts || true
	;;
  stop)
	echo -n "Stopping $DESC:"
	
	if [ -x "$RFCOMM" ] ; then
		echo -n " rfcomm"
		"$RFCOMM" release all
	fi
	
	echo -n " sdpd"
	killall "$SDPD" > /dev/null 2>&1 || true
	
	echo -n " hcid"
	killall "$HCID" > /dev/null 2>&1 || true
	
	echo -n " hidd"
	killall "$HIDD" > /dev/null 2>&1 || true

	echo -n " pand"
	killall "$PAND" > /dev/null 2>&1 || true

	echo -n " dund"
	killall "$DUND" > /dev/null 2>&1 || true
	
	echo "."

	stop_uarts
	;;
  restart|force-reload)
	echo "Restarting $DESC:"
	$0 stop
	sleep 5 #hidd needs longer time to finish
	$0 start
	echo "."
	;;
  *)
	N=/etc/init.d/bluetooth
	echo "Usage: "$N" {start|stop|restart|force-reload}" >&2
	exit 1
	;;
esac

exit 0
