#!/bin/bash

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

eepromConfig=$icronFirmwareDir/icron_eeprom_default.bin
eepromWriter=$(dirname $0)/ge_eeprom.py
macWriter=$(dirname $0)/add_mac.sh
exitCode=0

# 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

# 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

#Add mac crc to eeprom config file
/bin/bash $macWriter $eepromConfig $(get-system-info mac Icron_1)

requestId=$(curl -s -X POST ${blueriverIp}:$port/api/device/$avx \
   -H 'Content-Type: application/json' \
   -d '{"op" : "icron:program:eeprom","port_index":0}' | jq '.request_id')
echo "Asking Icron to enter eeprom updater mode, answer in $requestId requestId"

waitForSuccess $requestId $ignoreNoSuchRequestId
echo "Icron entered eeprom updater mode"

echo "Writing eeprom"
errorCode=$(python3 $eepromWriter $uart1Avx write < $eepromConfig 2>&1)

if [[ $errorCode == *"Traceback (most recent call last):"* ]]; then
    exitCode=1
fi

requestId=$(curl -s -X POST ${blueriverIp}:$port/api/device/$avx \
   -H 'Content-Type: application/json' \
   -d '{"op" : "icron:program:none"}' | jq '.request_id')
echo "Asking Icron to quit eeprom updater mode, answer in $requestId requestId"

waitForSuccess $requestId $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 eeprom updater mode"
exit $exitCode
