#!/bin/bash
ICRON_PROGRAMMER_BOARD_CONFIG="/etc/lwr/static-config/icron-programmer/board_config.env"

if [ -f "$ICRON_PROGRAMMER_BOARD_CONFIG" ]; then
    source "$ICRON_PROGRAMMER_BOARD_CONFIG"
fi

icronName="Icron_1"
avx=$(/usr/bin/get-system-info mac Avx_1 | sed 's/://g' | tr '[:upper:]' '[:lower:]') #this is a simpler method than discovering all avx devices and making sure we find the local one
blueriverIp=127.0.0.1
port=8080

icronFirmwareVersionXml=/mnt/storage/permanent/fwversion/icron_1.xml
icronEepromVersionXml=/mnt/storage/permanent/fwversion/icron_eeprom_1.xml
icronFirmwareDir=/usr/lib/firmware/lwr

waitForSuccess() {
    local requestId=$1
    local ignoreNoSuchRequestId=${2:-0}
    while true; do
        local statusFull=$(curl -s ${blueriverIp}:$port/api/request/$requestId \
            -H 'Content-Type: application/json')
        local status=$(jq '.status' <<< ${statusFull})
        echo "Status of request: $status"

        if [ "$status" == "\"SUCCESS\"" ]; then
            return 0
        elif [ "$status" == "\"ERROR\"" ]; then

            # Special case for icron:program when AVX is not claimed in Blueriver 3.8
            if [ "$ignoreNoSuchRequestId" == 1 ]; then
                local errorReason=$(jq '.error.reason' <<< ${statusFull})
                local errorMessage=$(jq '.error.message' <<< ${statusFull})
                if [ "$errorReason" == "\"ILLEGAL_ARGUMENT\"" ] && [ "$errorMessage" == "\"No such request ID\"" ]; then
                    echo "Request failed with ${errorReason} and ${errorMessage}, deliberately treating as success"
                    return 0
                fi
            fi

            return 1
        fi
        sleep 1
    done
}

waitForAvx() {
    local avxToDiscover=$1
    while true; do
        local deviceId=$(curl -s ${blueriverIp}:$port/api/device/$avxToDiscover \
            -H 'Content-Type: application/json' | jq '.result.devices[] | .device_id' 2>&1)
        if [ "$deviceId" == "\"$avxToDiscover\"" ]; then
            break
        elif [[ "$deviceId" == *"jq: error"* ]]; then
            echo "Avx not available on the network"
        fi
        sleep 5
    done
}

enterNonProgrammingMode() {
    local avxToStopProgramming=$1
    local ignoreNoSuchRequestId=${2:-0}
    local exitcode=1
    local requestIdFull
    local requestId

    while [[ exitcode -ne 0 ]]; do
        #this command pulls the BOOT_SEL0 high and also resets the icron on the I_RESET pin
        requestIdFull=$(curl -s -X POST ${blueriverIp}:$port/api/device/$avxToStopProgramming \
            -H 'Content-Type: application/json' \
            -d '{"op" : "icron:program:none"}')
        requestId=$(jq '.request_id' <<< ${requestIdFull})

        echo "Asking Icron to enter non-programming mode, answer in $requestId requestId"
        waitForSuccess $requestId $ignoreNoSuchRequestId
        exitcode=$?
        if [[ exitcode -eq 1 ]]; then #error, try process again
            sleep 1
        fi
    done
}

rebootAvx() {
    local avxToReboot=$1
    local status

    while true; do
        status=$(curl -s -X POST ${blueriverIp}:$port/api/device/$avxToReboot \
            -H 'Content-Type: application/json' -d '{"op" : "reboot"}' | jq '.status')

        echo "Status of request: $status"
        if [ "$status" == "\"SUCCESS\"" ]; then
            return
        fi

        sleep 1
    done
}

claimAvx() {
    local avxToClaim=$1
    local exitcode=1
    local requestId

    while [[ exitcode -ne 0 ]]; do
        requestId=$(curl -s -X POST ${blueriverIp}:$port/api/device/$avxToClaim \
            -H 'Content-Type: application/json' \
            -d '{"op" : "claim"}' | jq '.request_id')

        echo "Claim AVX device, answer in $requestId requestId"
        waitForSuccess $requestId
        exitcode=$?
        if [[ exitcode -eq 1 ]]; then #error, try process again
            sleep 1
        fi
    done
}

releaseAvx() {
    local avxToRelease=$1
    local exitcode=1
    local requestId

    while [[ exitcode -ne 0 ]]; do
        requestId=$(curl -s -X POST ${blueriverIp}:$port/api/device/$avxToRelease \
            -H 'Content-Type: application/json' \
            -d '{"op" : "release"}' | jq '.request_id')

        echo "Release AVX device, answer in $requestId requestId"
        waitForSuccess $requestId
        exitcode=$?
        if [[ exitcode -eq 1 ]]; then #error, try process again
            sleep 1
        fi
    done
}

isAvxClaimed() {
    local avxToCheck=$1
    local claimedState=$(curl -s ${blueriverIp}:$port/api/device/$avxToCheck \
        -H 'Content-Type: application/json' \
        -d '{"op" : "get", "subset" : "settings"}' | jq '.result.devices[].configuration.claimed' 2>&1)
    if [ "$claimedState" == "true" ]; then
        return 0
    else
        return 1
    fi
}

isBlueriverVersionAtLeast() {
    local minimumMajorVersion=$1
    local minimumMinorVersion=$2

    local versionString=$(curl -s -X GET ${blueriverIp}:$port/api \
        -H 'Content-Type: application/json' | jq --raw-output '.result.version')
    local majorVersion=$(echo "$versionString" | cut -d . -f 1)
    local minorVersion=$(echo "$versionString" | cut -d . -f 2)

    if [ "$majorVersion" -gt "$minimumMajorVersion" ]; then
        return 0
    elif [ "$majorVersion" -eq "$minimumMajorVersion" ] && [ "$minorVersion" -ge "$minimumMinorVersion" ]; then
        return 0
    else
        return 1
    fi
}
