#!/bin/bash

# echo "$@"

urls=()
options=()

while [[ $# -gt 0 ]]; do
    case "$1" in
        --url)
            urls+=("$2")
            shift 2
            ;;
        *)
            options+=("$1")
            shift 1
            ;;
    esac
done

if [[ ${#urls[@]} -eq 0 ]]; then
    echo "No URLs provided"
    exit 1
fi

original_output=""
temp_file=""

for i in "${!options[@]}"; do
    if [[ "${options[i]}" == "-o" ]]; then
        output_file="${options[i+1]}"
        temp_file=$(mktemp)

        options[i+1]="$temp_file"
        original_output="$output_file"
        break
    fi
done

output=""
for url in "${urls[@]}"; do
    #echo "curl -s ${options[@]} $url"
    output=$(eval "curl -s ${options[@]@Q} '$url' --fail")
    if [[ $? -eq 0 ]]; then

        # Skip and try the next reference URL when the response is a JSON-RPC error OR has a
        # null result (a lagging endpoint that doesn't have the requested block/data yet).
        # Without the result==null check the first endpoint's {"result":null} was accepted as
        # success and the remaining fallback URLs were never tried.
        # $temp_file only exists when curl was called with -o (see the -o loop above).
        # When a caller omits -o, the body is already in $output, so reading cat "" would
        # emit "cat: '': No such file or directory". Read from whichever place holds the body.
        response_body="$output"
        if [ -n "$temp_file" ]; then
            response_body=$(cat "$temp_file")
        fi
        if echo "$response_body" | jq -e 'has("error") or (.result == null)' > /dev/null 2>&1; then
            continue  # Try the next URL
        fi

	if [ -n "$original_output" ]; then
	    #echo "$(cat $temp_file)"
	    cat "$temp_file" > "$original_output"
	fi
	
        echo "$output"
        exit 0
    else
        continue
    fi
done

# Write the final output to the original output file if specified
if [ -n "$original_output" ]; then
    cat "$temp_file" > "$original_output"
fi

# Print the output to stdout
echo "$output"
exit 1
