#!/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

#if called from outside with parameters
avx="${1:-$avx}"
uart1Avx="${2:-$uart1Avx}"
icronFirmwareDir="${3:-$icronFirmwareDir}"

if [ -z "${uart1Avx}" ]; then
    echo "Uart device is empty string, programming failed."
    exit 1
fi

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

# Blueriver 3.8 behaves differently to icron:program requests when AVX is not claimed
# Note: do not use brackets to call functions
if isBlueriverVersionAtLeast 3 8 && ! isAvxClaimed $avx; then
    ignoreNoSuchRequestId=1
fi

stty -F $uart1Avx 115200
parse_multicast_config

# stop stream RS232#0 (see TAUSW-5550)
# save the stream configuration so we can check it later
device_settings="$(get_device_settings "${avx}")"
stream0_config_before_stop="$(get_stream_config "${device_settings}" "RS232" 0)"
# get the destination to be restored at the end of the update
read -a stream0_destination < <(get_stream_destination "${stream0_config_before_stop}")
# do not stop the stream if the destination device ID can not be obtained
if [ "${#stream0_destination[@]}" -eq 2 ]; then
    echo "Stop stream ${avx} RS232 #0"
    stop_stream "${avx}" "RS232" 0 "${ignoreNoSuchRequestId}"
else
    echo "Unable to obtain the destination device ID from its IP address. RS232 #0 was not stopped."
fi

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

    # 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 ${blueriverIp}:$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 $ignoreNoSuchRequestId
    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
exitcode=$?
if [ ${exitcode} -eq 0 ]; then
    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
    exitcode=$?
fi

#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 $ignoreNoSuchRequestId

# restore the stopped stream
if [ "${#stream0_destination[@]}" -eq 2 ]; then
    echo "Restore stream ${avx} RS232 #0"
    stream0_dest_device="${stream0_destination[0]}"
    stream0_dest_index="${stream0_destination[1]}"
    switch_stream "${avx}" "RS232" 0 "${stream0_dest_device}" "${stream0_dest_index}" "${ignoreNoSuchRequestId}"
    # compare the restored state with the state before the stop
    device_settings="$(get_device_settings "${avx}")"
    stream0_config_after_restore="$(get_stream_config "${device_settings}" "RS232" 0)"
    stream0_config_diff="$(diff <(jq --sort-keys . <<< "${stream0_config_before_stop}") \
                                <(jq --sort-keys . <<< "${stream0_config_after_restore}"))"
    if [ $? -ne 0 ]; then
        echo "ERROR: The restored state of RS232 #0 does not match the state before the stop:"
        echo "${stream0_config_diff}"
    fi
fi

echo "Icron quit fw updater mode"
exit ${exitcode}
