#!/bin/sh
#
# Copyright 2009 - 2016 Wachendorff Elektronik GmbH & Co. KG
#

# stop
if [ "$1" == "stop" -o "$1" == "restart" ]; then
    /bin/echo "Dettaching Bluetooth module:"
    /usr/bin/killall hciattach
    /bin/echo teser >/sys/bus/platform/devices/bt_wt21.0/reset
fi

# start
if [ "$1" == "start" -o "$1" == "restart" ]; then
    /bin/echo "Attaching Bluetooth module: "
    
    # Check if bccmd is installed
    if [ ! -f "/usr/sbin/bccmd" ]; then
        /bin/echo "failed: bccmd not installed"
        exit 1
    fi
    
    # Check if hciattach is installed
    if [ ! -f "/usr/sbin/hciattach" ]; then
        /bin/echo "failed: hciattach not installed"
        exit 1
    fi
    
    # Create temporary PSR file for module bootstrapping
    /bin/echo "&025d = 0001" >/tmp/btconf.psr
    /bin/echo "&025d = 0001" >>/tmp/btconf.psr
    /bin/echo "&025d = 0001" >>/tmp/btconf.psr
    /bin/echo "&025d = 0001" >>/tmp/btconf.psr
    /bin/echo "&025d = 0001" >>/tmp/btconf.psr
    /bin/echo "&025d = 0001" >>/tmp/btconf.psr
    /bin/echo "&01f9 = 0001" >>/tmp/btconf.psr
    /bin/echo "&01be = 01d8" >>/tmp/btconf.psr
    /bin/echo "&01fe = 6590" >>/tmp/btconf.psr
    # TODO: get unique BDADDR from EEPROM/FLASH?
    /bin/echo "&0001 = 00ff ffff 0080 0007" >>/tmp/btconf.psr
    
    # Write configuration to module
    count=1
    error=1
    while [ "$count" -le 20 ]; do
        /usr/sbin/bccmd -d /dev/ttymxc0 -t bcsp psload -r /tmp/btconf.psr
        if [ "$?" -eq "0" ]; then
          error=0
          count=100
        fi
        count=`expr $count + 1`
    done
    /bin/rm -f /tmp/btconf.psr
    if [ "$error" -ne "0" ]; then
        echo "failed: link to module cannot be established"
        exit 1
    fi
    
    # Attach Bluetooth module
    /usr/sbin/hciattach /dev/ttymxc0 bcsp 115200 noflow
fi

