#!/bin/sh
# chkconfig: 2345 22 78
### BEGIN INIT INFO
# Provides:          bt-init
# Required-Start:    $network
# Required-Stop:     $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start bluetooth at boot time
# Description:       Enable service provided by bcm4339
# X-Start-Before:    
# X-Stop-After:      
# X-Timesys-Start-Number:  22
# X-Timesys-Stop-Number:  78
### END INIT INFO

# Bluetooth Enable/Reset Script
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#

# Variscite i.MX8QM SOM with Laird Sterling LWB5

BT_EN_GPIO=30
BT_BUF_GPIO=154
BT_TTY_DEV=/dev/ttyLP1
BT_FIRMWARE=/lib/firmware/brcm/bcm4339.hcd

HCICONFIG='which hciconfig'

enable_bt()
{
  if [ ! -d /sys/class/gpio/gpio${BT_EN_GPIO} ]; then
    echo ${BT_EN_GPIO} >/sys/class/gpio/export
    echo "out" > /sys/class/gpio/gpio${BT_EN_GPIO}/direction
  fi

  echo 0 > /sys/class/gpio/gpio${BT_EN_GPIO}/value
  sleep 1
  echo 1 > /sys/class/gpio/gpio${BT_EN_GPIO}/value

  if [ ! -d /sys/class/gpio/gpio${BT_BUF_GPIO} ]; then
      echo ${BT_BUF_GPIO} >/sys/class/gpio/export
      echo "out" > /sys/class/gpio/gpio${BT_BUF_GPIO}/direction
  fi
 
  echo 0 > /sys/class/gpio/gpio${BT_BUF_GPIO}/value
}

# Start BT hardware

bt_start()
{
  # Enable BT hardware
  enable_bt

  # Load BT firmware
  pidof brcm_patchram_plus > /dev/null && killall -9 brcm_patchram_plus
  brcm_patchram_plus --patchram ${BT_FIRMWARE} \
		         --enable_hci \
		         --no2bytes \
		         --baudrate 3000000 \
		         --scopcm=1,0,0,0,0,0,0,0,0,0 \
		         --tosleep 1000 ${BT_TTY_DEV} &
}

bt_stop()
{
  if [[ -n "HCICONFIG" ]]; then $HCICONFIG hci0 down; fi
  pidof brcm_patchram_plus > /dev/null && killall -9 brcm_patchram_plus

  # BT_BUF down
  echo 1 > /sys/class/gpio/gpio${BT_BUF_GPIO}/value

  # BT_EN down
  echo 0 > /sys/class/gpio/gpio${BT_EN_GPIO}/value
}

case "$1" in
    start)
        bt_start
    ;;
    stop)
        bt_stop
    ;;
    restart)
        $0 stop
        $0 start
    ;;
    *)
        echo "usage: $0 {start|stop|restart}"
    ;;
esac

exit 0
