#!/sbin/openrc-run
#
# OpenRC init script for the BlueZ bluetooth daemon.
#

description="Bluetooth subsystem"

DAEMON=/usr/sbin/bluetoothd
SDPTOOL=/usr/bin/sdptool
NOPLUGIN_OPTION=""

depend() {
	need localmount
	use dbus logger
	after bootmisc
}

load_defaults() {
	# shellcheck disable=SC1091
	[ -f /etc/default/bluetooth ] && . /etc/default/bluetooth
	# shellcheck disable=SC1091
	[ -f /etc/default/rcS ] && . /etc/default/rcS
}

run_sdptool() {
	local IFS o

	[ -x "$SDPTOOL" ] || return 1
	[ -n "${SDPTOOL_OPTIONS:-}" ] || return 0

	IFS=";"
	for o in $SDPTOOL_OPTIONS; do
		IFS=" "
		if [ "${VERBOSE:-}" != no ]; then
			$SDPTOOL $o
		else
			$SDPTOOL $o >/dev/null 2>&1
		fi
	done
}

start() {
	[ -x "$DAEMON" ] || return 0
	load_defaults

	if [ "${BLUETOOTH_ENABLED:-1}" = 0 ]; then
		ewarn "disabled; see /etc/default/bluetooth"
		return 0
	fi

	ebegin "Starting bluetooth"
	start-stop-daemon --start --background --exec "$DAEMON" -- $NOPLUGIN_OPTION
	eend $?

	run_sdptool || true
	return 0
}

stop() {
	[ -x "$DAEMON" ] || return 0
	load_defaults

	if [ "${BLUETOOTH_ENABLED:-1}" = 0 ]; then
		return 0
	fi

	ebegin "Stopping bluetooth"
	start-stop-daemon --stop --quiet --quiet --exec "$DAEMON" || true
	eend 0
}

status() {
	status_of_proc "$DAEMON" bluetooth
}
