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

BLUERIVER_CONFIG_FILE="/etc/blueriver.conf"

multicast_all_tx_default=224.1.1.253
multicast_all_rx_default=224.1.1.254

declare -A ip_to_device_group=(
    "${multicast_all_tx_default}" "ALL_TX"
    "${multicast_all_rx_default}" "ALL_RX"
)

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
}

get_device_settings() {
    local device_id="${1}"
    curl -s -X POST ${blueriverIp}:$port/api/device/${device_id} \
            -H 'Content-Type: application/json' \
            -d '{"op" : "get",
                "subset" : "settings"
                }'
}

get_stream_config() {
    local device_settings="${1}"
    local stream_type="${2}"
    local stream_index="${3}"

    jq --arg stream_type "${stream_type}" --arg stream_index "${stream_index}" \
        '.result.devices[0].streams | .[] | select(.type == $stream_type and .index == ($stream_index | tonumber))' <<< "${device_settings}"
}

post_blueriver_device_command() {
    local device_id="${1}"
    local json_command="${2}"
    local ignoreNoSuchRequestId=${3:-0}

    local response=$(curl -s -X POST ${blueriverIp}:$port/api/device/${device_id} \
            -H 'Content-Type: application/json' \
            -d "${json_command}")
    local request_id="$(jq '.request_id' <<< "${response}")"
    if [ "${request_id}" != "null" ]; then
        waitForSuccess "${request_id}" "${ignoreNoSuchRequestId}"
    else
        local error_reason=$(jq '.error.reason' <<< "${response}")
        local error_message=$(jq '.error.message' <<< "${response}")
        echo "The following request failed with ${error_reason} and ${error_message}:"
        echo "${json_command}"
        return 1
    fi
}

stop_stream() {
    local device_id="${1}"
    local stream_type="${2}"
    local stream_index="${3}"
    local ignoreNoSuchRequestId=${4:-0}
    local stop_stream_cmd="{\"op\" : \"stop\",
                \"stream_type\" : \"${stream_type}\",
                \"stream_index\" : ${stream_index},
                \"free\" : true
                }"
    post_blueriver_device_command "${device_id}" "${stop_stream_cmd}" "${ignoreNoSuchRequestId}"
}

switch_stream() {
    local device_id="${1}"
    local stream_type="${2}"
    local stream_index="${3}"
    local dest_device="${4}"
    local subscription_index="${5}"
    local ignoreNoSuchRequestId=${6:-0}
    local switch_stream_cmd="{\"op\" : \"switch:device\",
                \"stream_type\" : \"$stream_type\",
                \"stream_index\" : $stream_index,
                \"dest_device\" : \"$dest_device\",
                \"subscription_index\" : $subscription_index
                }"
    post_blueriver_device_command "${device_id}" "${switch_stream_cmd}" "${ignoreNoSuchRequestId}"
}

parse_multicast_config() {
    if [ ! -r "${BLUERIVER_CONFIG_FILE}" ]; then
        return 1
    fi
    while read device_group ip; do
        if [ "${device_group}" == "multicast_all_rx" ]; then
            ip_to_device_group["${ip}"]="ALL_RX"
        elif [ "${device_group}" == "multicast_all_tx" ]; then
            ip_to_device_group["${ip}"]="ALL_TX"
        fi
    done < <(grep -E "^ *multicast_all_(tx|rx) *= *[0-9]{1,3}(\.[0-9]{1,3}){3}" "${BLUERIVER_CONFIG_FILE}" \
            | sed "s/ *\([! =]*\) *= *\([! =]*\)/$1 $2/")
}

get_avx_device_group_by_ip() {
    local ip="${1}"
    if [[ -v ip_to_device_group["${ip}"] ]]; then
        echo -n "${ip_to_device_group["${ip}"]}"
    fi
}

get_avx_device_id_by_ip_address() {
    # Handle multicast IP addresses (ALL_RX, ALL_TX)
    local device_ip="${1}"
    local dest_device=$(get_avx_device_group_by_ip "${device_ip}")
    if [ ! -z "${dest_device}" ]; then
        echo -n "${dest_device}"
        return 0
    fi
    # Obtaining a specific device ID based on its IP address is currently not supported.
    return 1
}

get_stream_destination() {
    local stream_config="${1}"

    local stream_dest_index="$(jq '.configuration.dest_index' <<< "${stream_config}")"
    local stream_dest_device_address="$(jq -r '.configuration.address' <<< "${stream_config}")"
    local stream_dest_device="$(get_avx_device_id_by_ip_address "${stream_dest_device_address}")"
    if [[ ! -z "${stream_dest_device}" && ! -z "${stream_dest_index}" ]]; then
        echo -n "${stream_dest_device} ${stream_dest_index}"
        return 0
    fi
    return 1
}

