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

#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
echo "Icron quit eeprom updater mode"
exit $exitCode
