#!/bin/sh
#------------------------------------------------------------------
#
# ble_init - BLE related initialization/setup
#
# Copyright (c) 2019 by cisco Systems, Inc.
# All rights reserved.
#------------------------------------------------------------------
#set -x

. /usr/cisco/bin/sys_condition_func.sh

wait_for_capwapd() {
    local retry=10

    while ! is_capwap_started ; do
        sleep 5

        retry=$(expr $retry - 1)
        if [ $retry -eq 0 ]; then
            break
        fi
    done
}

flash_ble_fw() {
    wait_for_capwapd

    # Power up BLE chip
    /usr/bin/cli_scripts/reset_ble.sh 0 "ble_init"

    /usr/bin/cli_scripts/iot_fw_dnld.sh "ble" "default" "ble_init"

}

is_ignore_dio10_wordaround() {
    local ignore=$(/usr/bin/shared_printenv -n IGNORE_DIO10_WORDAROUND 2> /dev/null)

    if [ "$ignore" == "yes" ]; then
        # New board rev has hw fix.  Skip workaround
        return 0
    fi
    return 1
}

no_pulldown_on_DIO10_workaround() {
    if ! is_ignore_dio10_wordaround ; then
        flash_ble_fw
    fi
}

# returns OK if $1 contains $2
strstr() {
  [ "${1#*$2*}" = "$1" ] && return 1
  return 0
}

############################ Main ###############################

# Run sw workaround for missing pulldown resistor on DIO_10 pin
if [ -e /var/platform/ble_DIO10_no_pulldown ]; then
    no_pulldown_on_DIO10_workaround
fi

# Remove python binaries if AP is running ME mode
cmdline=`cat /proc/cmdline`
if strstr "$cmdline" "apmode=me" ; then
      rm -fr /usr/lib/python2.7 \
             /usr/bin/python* \
             /usr/bin/python2  > /dev/null 2>&1
fi
