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

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

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

if [ "$1" = "--cached" -a -f $CACHE_FILE ]; then
    shift
    BODY=$(cat $CACHE_FILE)
else
    [ "$1" = "--cached" ] && shift
    if hash curl 2>/dev/null; then
        # Using curl
        CODE=0
        while [ $CODE -ne 200 ]; do
            RESPONSE=$(curl --noproxy '*' --silent --write-out "\n%{http_CODE}\n" $METADATA_URL)
            CODE=$(echo "$RESPONSE" | sed -n '$p')
            BODY=$(echo "$RESPONSE" | sed '$d')

            if [ $CODE -eq 200 ]; then
                echo "$BODY" > /run/scw-metadata.cache
		ln -s scw-metadata.cache /run/oc-metadata.cache 2>/dev/null
                break
            fi
            sleep 5
        done
    else
        # Using wget
        for i in 1 2 3 4 5; do
            BODY=$(wget --no-proxy --quiet -O- $METADATA_URL)
	    echo "$BODY" | grep PRIVATE_IP >/dev/null
            if [ $? -eq 0 ]; then
		echo "$BODY" > /run/scw-metadata.cache
		ln -s scw-metadata.cache /run/oc-metadata.cache 2>/dev/null
                break
            fi
            sleep 2
        done
    fi
fi

if [ "$#" -ne 1 ]; then
    echo "$BODY"
else
    key="$1"
    echo "$BODY" | grep "^$key=" | sed "s/^[^=]*=//;s/^['\"]//;s/['\"]$//"
fi
