#! /bin/sh
### BEGIN INIT INFO
# Provides:          brcm40183-patch
# Required-Start:    $local_fs
# Required-Stop:
# X-Start-Before:    bluetooth  
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Patch firmware for brcm40183 Bluetooth adapter
# Description:       Patch firmware for brcm40183 Bluetooth adapter
### END INIT INFO

DEFAULTS="/etc/default/brcm40183"

# Include brcm40183 defaults if available
if [ -r "${DEFAULTS}" ]
then
	. "${DEFAULTS}"
fi

. /lib/lsb/init-functions

do_start () {

if [ ! -z $(/usr/sbin/hciconfig | /bin/grep UART | /usr/bin/cut -d: -f1) ]
then
    log_action_begin_msg "brcm40183 device allready initialized"
    log_action_end_msg 0
    /usr/bin/hcitool dev
else
    # Select MAC address
    if [ -z "$MAC_ADDR" ]; then
       log_warning_msg "No MAC_ADDR set in /etc/default/brcm40183, will use MAC 11:22:33:44:55:66"
       MAC_OPTIONS="--bd_addr 11:22:33:44:55:66"
    else
       MAC_OPTIONS="--bd_addr $MAC_ADDR"
    fi

    # Select tty port
    if [ -z "$PORT" ]; then
       log_warning_msg "No PORT set in /etc/default/brcm40183, will use ttyS1"
       PORT="ttyS1"
    fi

    # Start patching
    /bin/echo -en "" > /dev/$PORT      # pull down RTS on UART
    log_action_begin_msg  "Start pushing firmware to device and waiting max. 60sec to complete"

    /usr/bin/timeout 60s /usr/local/bin/brcm_patchram_plus -d --patchram /lib/firmware/ap6210/bcm20710a1.hcd --enable_hci --no2bytes --tosleep 1000 $MAC_OPTIONS /dev/$PORT > /tmp/brcm40183.firmware 2>&1

    case "$?" in
        0) log_action_end_msg 0
             # Enable interfaces
             /usr/sbin/hciattach /dev/$PORT any
             ;;
        *) log_action_end_msg 1
             /bin/echo "Check /tmp/brcm40183.firmware for messages."
             ;;
    esac
fi
}

case "$1" in
  start)
	do_start
	;;
  restart|reload|force-reload)
	echo "Error: argument '$1' not supported" >&2
	exit 3
	;;
  stop)
	# No-op
	;;
  status)
	/usr/bin/hcitool dev
	;;
  *)
	echo "Usage: brcm40183-patch.sh [start|stop|status]" >&2
	exit 3
	;;
esac

