#!/bin/bash
icronEnteredFirmwareUpdaterMode=/tmp/icronEnteredFirmwareUpdaterMode

#Waits until line received on uart contains substring given in parameter substr
waitForMessage() {
    local uart=$1
    local substr=$2
    local file=$3

    #built-in read command returns immediately if stream is empty and -e is not defined. -s prevents echoing back to Icron.
    while read -s -e line; do
    line="${line//[$'\r\n']}"
    [ -n "$line" ] && echo -e "Icron->AVX->${uart}: $line"
    if [[ "$line" == *"$substr"* ]]; then
        if [[ -n ${3+x} ]]; then
            touch ${file}
        fi
        break
    fi
    done < $uart
}

echo "Starting icron firmware update"
source $(dirname $0)/flash_icron_utils

flashwriter=$icronFirmwareDir/FlashWriterGoldenearsASIC.bin
firmware=$icronFirmwareDir/FirmwareGoldenearsASIC.bin

stty -F $uart1Avx 115200

exitcode=1
while [[ exitcode -ne 0 ]]; do
    enterNonProgrammingMode $avx

    # Wait until bootloader is loaded
    # Note: Icron sends this much sooner than the Blueriver request is served,
    #       so here we should watch for this message ASAP after sending Icron
    #       to programming mode.
    #Workaround #2 start listening to what icron says on uart in a separate thread, use result later
    rm -f ${icronEnteredFirmwareUpdaterMode}
    waitForMessage $uart1Avx "PlatformID" ${icronEnteredFirmwareUpdaterMode} &
    pid="$!"

    #this command pulls the BOOT_SEL0 low and also resets the icron on the I_RESET pin
    #port_index 0 means uart1Avx
    requestId=$(curl -s -X POST 127.0.0.1:$port/api/device/$avx \
       -H 'Content-Type: application/json' \
       -d '{"op" : "icron:program:firmware","port_index":0}' | jq '.request_id')
    echo "Asking Icron to enter fw updater mode, answer in $requestId requestId"

    # Wait for the success of sending Icron to programming mode
    waitForSuccess $requestId
    exitcode=$?
    if [[ exitcode -eq 1 ]]; then #error, try process again
        kill -s KILL ${pid}
        sleep 1
    fi
done

echo "AVX command was successful, waiting for sniffer process"
while [[ ! -f ${icronEnteredFirmwareUpdaterMode} ]]; do
    #do nothing, Workaround #2 wait is here
    sleep 1
done
rm -f ${icronEnteredFirmwareUpdaterMode}

#read an additional line from uart with 1s timeout
read -e -t 1 line < $uart1Avx

echo "Icron entered fw updater mode"

echo "Sending flashwriter"
sx $flashwriter < $uart1Avx > $uart1Avx

echo "Wait until flash is erased"
waitForMessage $uart1Avx "Done checking erase"

#read an additional line from uart with 1s timeout
read -e -t 1 line < $uart1Avx

echo "Sending firmware"
sx $firmware < $uart1Avx > $uart1Avx

#Sometimes Icron will send "Waiting for user to reset ..." and "Press enter (CR-LF) to reset ..." messages and sometimes it will not. Skipping uart check here.
enterNonProgrammingMode $avx

echo "Icron quit fw updater mode"
