#!/bin/bash

CURL_CONNTIMEOUT=2
CURL_MAXTIME=2
OVERALL_TRIES=5
SLEEP_INTERVAL=2

declare -a metadata_hosts=(
    "169.254.42.42"
    "[fd00:42::42]"
)

for _try in $(seq 1 "$OVERALL_TRIES"); do
    for host in "${metadata_hosts[@]}"; do
        response=$(
            curl --connect-timeout "$CURL_CONNTIMEOUT" \
                 --max-time "$CURL_MAXTIME" \
                 --noproxy '*' \
                 --silent \
                 --head \
                 --write-out "\n%{http_code}\n" \
                 "http://$host"
        )
        [[ $? != 0 ]] && continue

        code=$(echo "$response" | sed -n '$p')
        if [ "$code" = 200 ]; then
            echo "$host"
            exit 0
        fi
    done
    sleep $SLEEP_INTERVAL
done

echo "Error: No metadata host could be reached." >&2
exit 1
