#!/bin/sh

# NAME
#	bt_start
#
# SYNOPSIS
#	bt_start
#
# DESCRIPTION

COUNTER=0
MAXRETRY=30
type=$(cat /sys/kernel/secure/type)
subtype=$(cat /sys/kernel/secure/subtype)

bt_start ()
{
	echo bt_start
	
	while [  $COUNTER -lt $MAXRETRY ]; do
		/usr/bin/bluetooth-daemon 
		logger bluetooth-daemon returns error $?
		logger The counter is $COUNTER
		COUNTER=$(($COUNTER + 1))
		sleep 1
	done
	echo bt_daemon exits no bt hardware detected
	logger bluetooth-daemon exits no bt hardware detected
}

if [ "$1" = "start" ]
then
#   in this version bt firmware is programmed by MQX
    if [ "$type" -eq 1 ] && ( [ "$subtype" -eq 2 ] || [ "$subtype" -eq 3 ] || [ "$subtype" -ge 5 ] )
    then
	logger BT firmware programmed by MQX
	logger starting bluetooth-daemon
	bt_start &
	logger bluetooth-daemon started
    else
        logger nordic bluetooth device not detected
    fi
fi
if [ "$1" = "stop" ]
then
#kill with 15(SIGINT) so daemon releases all resources and quits nicely
    if [ "$type" -eq 1 ] && ( [ "$subtype" -eq 2 ] || [ "$subtype" -eq 3 ] || [ "$subtype" -ge 5 ] )
    then
	killall -s 15 bluetooth-daemon
    fi
fi
