#!/bin/bash
#
#

DO_API_URL='https://api.digitalocean.com/v2/images?private=true'
DO_API_TOKEN='{{ digitalocean_authentication_token }}'
STAGE={{ stage }}

NODE_EXPORTER_TXT_DIR='/var/lib/prometheus/node-exporter'
METRICS_FILE="${NODE_EXPORTER_TXT_DIR}/do_metrics.prom"

DATE=$(date +%s)
DO_HEADERS_FILE="/tmp/do_headers_${DATE}"

curl -s -I -H "Authorization: Bearer $DO_API_TOKEN" "${DO_API_URL}" -D ${DO_HEADERS_FILE} -o /dev/null

RATE_LIMIT__LIMIT=$(grep ratelimit-limit $DO_HEADERS_FILE | awk '{print $NF}' | sed 's/\r//g' )
RATE_LIMIT__REMAINING=$(grep ratelimit-remaining $DO_HEADERS_FILE | awk '{print $NF}' | sed 's/\r//g')

cat <<EOF > $METRICS_FILE
# HELP digitalocean_api_ratelimit_remaining
# TYPE digitalocean_api_ratelimit_remaining gauge
digitalocean_api_ratelimit_remaining $RATE_LIMIT__REMAINING
# HELP digitalocean_api_ratelimit_limit
# TYPE digitalocean_api_ratelimit_limit gauge
digitalocean_api_ratelimit_limit $RATE_LIMIT__LIMIT
EOF
