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

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

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

USERDATA_URL=${USERDATA_URL:-"http://${USERDATA_HOST}/user_data"}

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

get() {
    local url=$1
    local try response code body curl_error

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

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

        [[ $code == 404 ]] && {
            echo "No such key." >&2
            exit 1
        }

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

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

patch() {
    local url="$1"
    local data="$2"
    local try response code body

    for try in $(seq 1 "$OVERALL_TRIES"); do
        response=$(
            curl --local-port 1-1024 \
                 --connect-timeout "$CURL_CONNTIMEOUT" \
                 --max-time "$CURL_MAXTIME" \
                 --noproxy '*' \
                 --silent \
                 --write-out "\n%{http_code}\n" \
                 --request PATCH \
                 --header "Content-Type: text/plain" \
                 --data "$data" \
                 "$url"
        )
        code=$(echo "$response" | sed -n '$p')

        [[ $code == 204 ]] && break

        if ((try < OVERALL_TRIES)); then
            sleep $SLEEP_INTERVAL
        else
            echo "Userdata could not be updated (HTTP $code). Aborting..." >&2
            exit 1
        fi
    done
}

if (($# >= 2)); then
    patch "$USERDATA_URL/$1" "$2"
else
    get "$USERDATA_URL/$1"
fi
