#!/bin/sh

btt_reset()
{
	rm -rf /var/lib/bluetooth/*
	pkill bluetoothd
	
	/usr/sbin/bluetoothd
	sleep 1
	hciconfig up >/dev/null 2>&1
	sleep 2
	hciconfig hci0 noencrypt
	hciconfig hci0 piscan
	hciconfig hci0 name "bluez4"
	hciconfig hci0 pageto 65535
	
	sleep 2
	hciconfig -a
}

btt_scan()
{
	echo "Scan nearby bluetooth normal devices ..."
	hcitool scan
}

btt_lescan()
{
	echo "Scan nearby bluetooth LE devices ..."
	hcitool lescan
}

btt_a2dp()
{
	local mac=$1
	local asoundconf="/etc/asound.conf"

	sdptool add a2snk
	sdptool add a2src
	sdptool add avrct
	sdptool add avrtg
	sdptool add hf
	sdptool add hs
	sleep 1

	if grep -q "pcm.bluetooth" $asoundconf ; then
		if ! grep -q "device $mac" $asoundconf ; then 
			sed -i -e "s/device.*$/device $mac/g" $asoundconf
		fi
	else
		echo "" >> $asoundconf
		echo "pcm.bluetooth{" >> $asoundconf
		echo "    type bluetooth" >> $asoundconf
		echo "    device $mac" >> $asoundconf
		echo "    profile \"hifi\"" >> $asoundconf
		echo "}" >> $asoundconf
	fi

	echo "Bind to $mac ..."
	bluez-simple-agent hci0 $mac || {
		echo "bluez-simple-agent failed!"
		exit 1
	}

	echo "Connect $mac ..."
	bluez-test-audio connect $mac || {
		echo "audio connect failed!"
		exit 1
	}

	echo "Connection result ..."
	hcitool con
		
	echo "Play audio ..."
	aplay -D bluetooth /root/examples/bluetooth/test.wav
}

btt_kbd()
{
	local mac="$1"

	sdptool add keyb

	echo "Bind to $mac ..."
	echo -en "\n## Press the same code in keyboard and press enter to confirm!## \n"
	bluez-simple-agent hci0 $mac || {
		echo "bluez-simple-agent failed!"
		exit 1
	}

	hidd --connect $mac

	
	echo -en "\n## Press any key in keyboard and it will be displayed in the terminal ##\n"
}

btt_health()
{
	local tmpdir="/root/examples/bluetooth/test"
	mkdir -p $tmpdir
	ieee11073-sink-example $tmpdir $tmpdir/test.log 0 0
}

btt_usage()
{
	echo "usage: btt command [args...] "
	echo "  btt reset"
	echo "  btt scan"
	echo "  btt lescan"
	echo "  btt a2dp <bt-address-of-A2DP-device>"
	echo "  btt kbd <bt-address-of-A2DP-device>"
	echo ""
}

case $1 in
	reset)
		btt_reset
		;;
	scan)
		btt_scan
		;;
	lescan)
		btt_lescan
		;;
	a2dp)
		echo $2 | grep -q "[[:digit:]]\{2\}:*" || {
			btt_usage
			exit 1
		}
		btt_a2dp $2
		;;
	kbd)
		btt_kbd $2
		;;
	health)
		btt_health
		;;
	*)
		btt_usage
		exit 1
		;;
esac
	
