#!/bin/bash
# description "executable which retrieves server metadata (TEXT)"
# 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

CACHE_FILE=/run/scw-metadata.cache
METADATA_URL=${METADATA_URL:-"http://${METADATA_HOST}/conf"}

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

if [[ $1 == --cached ]] && [[ -f $CACHE_FILE ]]; then
    shift
    body=$(cat $CACHE_FILE)
else
    [[ $1 == --cached ]] && shift
    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_URL"
        )
        curl_error=$?

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

        [[ $code == 200 ]] && [[ $curl_error == 0 ]] && break

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

echo "$body" > /run/scw-metadata.cache
ln -s scw-metadata.cache /run/oc-metadata.cache 2>/dev/null

if (($# != 1)); then
    echo "$body"
else
    key="$1"
    if ! data=$(echo "$body" | grep "^$key="); then
        echo "No such key." >&2
        exit 0
    fi
    echo "$data" | sed "s/^[^=]*=//;s/^['\"]//;s/['\"]$//"
fi
