#!/bin/bash
# description "executable which retrieves server metadata (JSON)"
# author "Scaleway <opensource@scaleway.com>"

export PATH="${PATH:+$PATH:}/usr/bin:/bin"

METADATA_HOST="$(scw-get-metadata-host)"
if [[ -z $METADATA_HOST ]] && [[ -z $METADATA_URL ]]; then
    echo "No metadata host/URL detected nor provided. Aborting..." >&2
    exit 1
fi

METADATA_URL=${METADATA_URL:-"http://${METADATA_HOST}/conf"}
METADATA_JSON_URL="${METADATA_URL}?format=json"

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

for try in $(seq 1 "$OVERALL_TRIES"); do
    response=$(
        curl --connect-timeout "$CURL_CONNTIMEOUT" \
             --max-time "$CURL_MAXTIME" \
             --noproxy '*' \
             --silent \
             --write-out "\n%{http_code}\n" \
             "$METADATA_JSON_URL"
    )
    curl_error=$?

    code=$(echo "$response" | sed -n '$p')
    body=$(echo "$response" | sed '$d')

    [[ $code == 200 ]] && [[ $curl_error == 0 ]] && {
        echo "$body"
        break
    }

    if ((try < OVERALL_TRIES)); then
        sleep $SLEEP_INTERVAL
    else
        echo "Metadata could not be retrieved. Aborting..." >&2
        exit 1
    fi
done
