#!/bin/bash

### BEGIN INIT INFO
# Provides:             brcm_patchram_plus
# Required-Start:       $syslog
# Required-Stop:        $local_fs $syslog
# Default-Start:        2 3 4 5
# Default-Stop:	        0 1
# Short-Description:    brcm_patchram_plus
### END INIT INFO

#
# Bluetooth hardware init (AP6212/BCM43438) & hciattach
#

DESCRIPTION="Bluetooth hardware init (AP6212/BCM43438) & hciattach"
EXECUTABLE=${EXECUTABLE=/bin/brcm_patchram_plus}

set -e
source /lib/lsb/init-functions

# For testing purposes: Switch off systemd integration by
#   - commenting out "source /lib/lsb/init-functions" above
#   - uncommenting the log functions below
#
#log_daemon_msg() {
#        echo $1
#}
#log_end_msg() {
#        echo $1
#}
#log_failure_msg() {
#        echo $1
#}
#log_success_msg() {
#        echo $1
#}
#log_action_msg() {
#        echo $1
#}

test -x $EXECUTABLE || exit 0
export PATH="${PATH:+$PATH:}/usr/sbin:/sbin"

DEVICE=${DEVICE=ttySAC1}
BUMPRTSCTS=${BUMPRTSCTS=/bin/bumpRTSCTS}
PIDFILE=${PIDFILE=/var/run/brcm_patchram_plus.${DEVICE}.pid}
MACADDRESS=`md5sum /sys/devices/platform/cpu/uuid | cut -b 1-12 | sed -r ':1;s/(.*[^:])([^:]{2})/\1:\2/;t1'`
BT_BCM_RFKILL=/sys/devices/platform/bt_bcm.0/rfkill/rfkill0
#VERBOSE=--verbose

case "$1" in
  start)
        log_daemon_msg "Starting ${DESCRIPTION}" "brcm_patchram_plus"
        RFKILL=`cat ${BT_BCM_RFKILL}/state`
        if [ $RFKILL -ne 1 ]; then
          echo "1" > ${BT_BCM_RFKILL}/state
        fi
        ${BUMPRTSCTS} /dev/${DEVICE}
        sleep 0.2
        start-stop-daemon ${VERBOSE} --start --background --oknodo --make-pidfile --pidfile ${PIDFILE} --exec ${EXECUTABLE} -- --patchram /lib/firmware/ap6212/bcm43438a0.hcd --bd_addr $MACADDRESS --no2bytes --tosleep 5000 --enable_hci /dev/${DEVICE}
        RC=$?
        # wait/loop until hci0 has been created
        until hcitool dev | grep hci0 >/dev/null 2>&1; do sleep 0.2; done
        if [ $RFKILL -eq 0 ]; then
          rfkill block bluetooth
        fi
        log_end_msg $RC
        ;;
  stop)
        log_daemon_msg "Stopping ${DESCRIPTION}" "brcm_patchram_plus"
        start-stop-daemon ${VERBOSE} --stop --oknodo --remove-pidfile --pidfile ${PIDFILE} --retry 5
        RC=$?
        # wait/loop until hci0 has gone
        while [ `hcitool dev | grep hci0 | wc -l` -ne 0 ]; do sleep 0.2; done
        log_end_msg $RC
        ;;
  reload|force-reload|restart)
        "$0" stop
        sleep 1
        "$0" start
        ;;
  status)
        start-stop-daemon ${VERBOSE} --status --pidfile ${PIDFILE}
        if [ $? -eq 0 ] ; then
          log_success_msg "brcm_patchram_plus is running as PID `cat ${PIDFILE}`"
        else
          log_failure_msg "brcm_patchram_plus is not running"
        fi
        ;;
  *)
        log_action_msg "Usage: $0 {start|stop|reload|status}"
        exit 1
esac

exit $?

