#!/bin/bash

source /usr/lib/distro-xml-fw-checker.sh
source $(dirname $0)/flash_icron_utils

do_ic_update_process() {
    local firmware_name=$1
    local firmware_xml_path=$2
    local eeprom_name=$3
    local eeprom_xml_path=$4

    /usr/bin/get-system-info macNames | grep -q "${icronName}"
    if [ $? -ne 0 ]; then
        echo "${icronName} mac address missing from UID!"
        return 1
    fi

    is_firmware_uptodate $firmware_name $firmware_xml_path
    local firmware_uptodate_status=$?
    is_firmware_uptodate $eeprom_name $eeprom_xml_path
    local eeprom_uptodate_status=$?

    if [[ firmware_uptodate_status -ne 0 || eeprom_uptodate_status -ne 0 ]]; then
        systemctl start blueriver.service

        #Waiting 15 seconds after blueriver start-up and avx start-up 
        #(this is required because the AVX does an additional recconnecting sequence if an RX device is connected)
        echo "Waiting 15 seconds after starting blueriver"
        sleep 15

        claimAvx $avx
        #Waiting 2 seconds is required due to a device reconnect after AVX claim
        echo "Waiting 2 seconds after claiming AVX"
        sleep 2
        
        echo "Start updating icron firmware"
        /bin/bash $(dirname $0)/flash_icron_firmware
        if [[ $? -ne 0 ]]; then
            echo "Firmware programming failed!"
        else
            commit_firmware_version_xml $firmware_name $firmware_xml_path
        fi

        echo "Start updating icron eeprom content"
        /bin/bash $(dirname $0)/flash_icron_eeprom
        if [[ $? -ne 0 ]]; then
            echo "Eeprom programming failed!"
        else
            commit_firmware_version_xml $eeprom_name $eeprom_xml_path    
        fi

        releaseAvx $avx
        #Waiting ~2 seconds is required due to a device reconnect after AVX release
        echo "Waiting 2 seconds after releasing AVX"
        sleep 2

        echo "Rebooting AVX"
        rebootAvx $avx
        
        systemctl stop blueriver.service
    else
        echo "Icron firmware and eeprom is up-to-date, update is not required"
    fi
}

do_ic_update_process "icron" "$icronFirmwareVersionXml" "icron-eeprom" "$icronEepromVersionXml"