#!/bin/sh

echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 60 BT +++++++++++++++++++++++++++++++++++++"

rm -fr /etc/asound.conf

#BLUEALSA_SBC_QUALITY=low
#BLUEALSA_SBC_QUALITY=medium
BLUEALSA_SBC_QUALITY=high
#BLUEALSA_SBC_QUALITY=xq
#BLUEALSA_SBC_QUALITY=xq+

BLUETOOTHD_ARGS="-d -E"
BLUEALSA_ARGS="-p a2dp-source --sbc-quality=$BLUEALSA_SBC_QUALITY"

hci_tst_cmd="hciconfig name"
hci_tst_up="UP RUNNING"
hci_tst_down="DOWN"

hci_init_cmd="hciattach -s 115200 ttymxc4 qca 4000000 flow nosleep"

hci_state_get()
{
	hci_tst=$($hci_tst_cmd)
	if [ "$(echo "$hci_tst" | grep "$hci_tst_up")" != "" ]
	then
		echo 2
	else
		if [ "$(echo "$hci_tst" | grep "$hci_tst_down")" != "" ]
		then
			echo 1
		else
			echo 0
		fi
	fi
}


start() {
	echo "Starting BT audio output..."
	echo "    codec: SBC, quality: $BLUEALSA_SBC_QUALITY"

	hci_init_ok=0
	hci_state=$(hci_state_get)

	if [ $hci_state -eq 2 ]
	then
		hci_init_ok=1
	else
		if [ $hci_state -eq 0 ]
		then
			$hci_init_cmd
		fi

		if [ $(hci_state_get) -ne 0 ]
		then
			hci_init_ok=1
		fi
	fi

	if [ $hci_init_ok -eq 1 ]
	then
		start-stop-daemon -b -S -q -m -p /var/run/bluetoothd.pid --exec /usr/libexec/bluetooth/bluetoothd -- $BLUETOOTHD_ARGS
		start-stop-daemon -b -S -q -m -p /var/run/bluealsa.pid --exec bluealsa -- $BLUEALSA_ARGS
		start-stop-daemon -K -t -p /var/run/bluetoothd.pid && echo -e 'power off' | bluetoothctl >/dev/null 2>&1 &
		modprobe snd-aloop
		echo "BT a2dp ready"
		cp -f /etc/asound.FULL /etc/asound.conf
	else
		echo "An error occurred while initializing the HCI. BT cannot be used."
		cp -f /etc/asound.TINY /etc/asound.conf
	fi
}

stop() {
	echo "Stopping BT audio output..."
	modprobe -r snd-aloop
	start-stop-daemon -K -t -p /var/run/bluetoothd.pid && echo -e 'power off' | bluetoothctl >/dev/null 2>&1 &
	start-stop-daemon -K -q -p /var/run/bluealsa.pid
	start-stop-daemon -K -q -p /var/run/bluetoothd.pid
	echo "OK"
}

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

