#!/bin/sh

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DESC=bluetooth

DAEMON=/usr/libexec/bluetooth/bluetoothd

# If you want to be ignore error of "org.freedesktop.hostname1",
# please enable NOPLUGIN_OPTION.
# NOPLUGIN_OPTION="--noplugin=hostname"
NOPLUGIN_OPTION=""
SSD_OPTIONS="--oknodo --quiet --exec $DAEMON -- $NOPLUGIN_OPTION"
DBUS_INIT=/etc/init.d/dbus-1
DBUS_WAS_STARTED=0
RETRY_SECONDS=30

test -f $DAEMON || exit 0

# FIXME: any of the sourced files may fail if/with syntax errors
test -f /etc/default/bluetooth && . /etc/default/bluetooth
test -f /etc/default/rcS && . /etc/default/rcS

set -e

dbus_ready() {
	[ -S /run/dbus/system_bus_socket ] || return 1
	dbus-send --system --dest=org.freedesktop.DBus --type=method_call --print-reply / org.freedesktop.DBus.ListNames >/dev/null 2>&1
}

start_dbus() {
	dbus_ready && return 0
	DBUS_WAS_STARTED=1
	[ -x "$DBUS_INIT" ] && "$DBUS_INIT" start >/dev/null 2>&1 || true
	dbus_ready
}

start_later() {
	(
		i=0
		while [ $i -lt $RETRY_SECONDS ]; do
			if dbus_ready; then
				start-stop-daemon --start --background $SSD_OPTIONS || true
				start_uarts
				exit 0
			fi
			sleep 1
			i=$((i+1))
		done
	) &
}

start_uarts() {
	[ -r /etc/bluetooth/uart.conf ] || return 0
	grep -qvwE '^[[:space:]]*(#|$)' /etc/bluetooth/uart.conf || return 0
	grep -vwE '^[[:space:]]*(#|$)' /etc/bluetooth/uart.conf | while read i; do
		$i > /dev/null 2>&1
	done

	hciconfig hci0 reset || true
}

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

case $1 in
  start)
	echo -n "Starting $DESC: "
	if test "$BLUETOOTH_ENABLED" = 0; then
		echo "disabled (see /etc/default/bluetooth)."
		exit 0
	fi
	if ! start_dbus; then
		echo "waiting for D-Bus."
		start_later
		exit 0
	fi
	if [ "$DBUS_WAS_STARTED" = "1" ]; then
		start-stop-daemon --stop --quiet --oknodo --exec $DAEMON >/dev/null 2>&1 || true
	fi
	start-stop-daemon --start --background $SSD_OPTIONS
	echo "${DAEMON##*/}."
	start_uarts
  ;;
  stop)
	echo -n "Stopping $DESC: "
	if test "$BLUETOOTH_ENABLED" = 0; then
		echo "disabled (see /etc/default/bluetooth)."
		exit 0
	fi
	start-stop-daemon --stop $SSD_OPTIONS
	echo "${DAEMON##*/}."
	stop_uarts
  ;;
  restart|force-reload)
	$0 stop
	sleep 1
	$0 start
  ;;
  status)
	 pidof ${DAEMON} >/dev/null
	 status=$?
        if [ $status -eq 0 ]; then
                 echo "bluetooth is running."
        else
                echo "bluetooth is not running"
        fi
        exit $status
   ;;
   *)
	N=/etc/init.d/bluetooth
	echo "Usage: $N {start|stop|restart|force-reload|status}" >&2
	exit 1
	;;
esac

exit 0

# vim:noet
