#!/bin/bash
set -e

API_URL=${API_URL:-"https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_SERVICE_PORT"}
NSQ_TOPIC_URL=${NSQ_TOPIC_URL:-"http://$DRYCC_NSQD_SERVICE_HOST:$DRYCC_NSQD_SERVICE_PORT/topic/create?topic=$NSQ_CONSUMER_TOPIC"}

export BEARER_TOKEN_PATH TOKEN NODE_NAME NODE_IP AGENT_HOSTNAME
BEARER_TOKEN_PATH=/var/run/secrets/kubernetes.io/serviceaccount/token
TOKEN="$(cat $BEARER_TOKEN_PATH)"
NODE_NAME="$(curl -s "$API_URL/api/v1/namespaces/$POD_NAMESPACE/pods/$HOSTNAME" --header "Authorization: Bearer $TOKEN" --insecure | jq -r '.spec.nodeName')"
echo "Node Name set (${NODE_NAME})"
NODE_IP="$(curl -s "$API_URL/api/v1/namespaces/$POD_NAMESPACE/pods/$HOSTNAME" --header "Authorization: Bearer $TOKEN" --insecure | jq -r '.status.hostIP')"
echo "Node IP set (${NODE_IP})"
AGENT_HOSTNAME=$NODE_NAME

if [ -n "$DRYCC_NSQD_SERVICE_HOST" ]; then
  echo "Creating topic with URL: ${NSQ_TOPIC_URL}"
  curl -s -X POST "${NSQ_TOPIC_URL}"
fi

if [ -n "$ENABLE_KUBERNETES" ]; then
  export KUBERNETES_BEARER_TOKEN_PATH=${BEARER_TOKEN_PATH}
  export KUBERNETES_URL="http://${NODE_IP}:10255"
  echo "Setting KUBERNETES_URL: $KUBERNETES_URL"
fi

if [ -n "$ENABLE_PROMETHEUS" ]; then
  export PROMETHEUS_BEARER_TOKEN_PATH=${BEARER_TOKEN_PATH}
  export PROMETHEUS_URLS="\"$API_URL/api/v1/proxy/nodes/$NODE_NAME/metrics\", \"$API_URL/metrics\""
  echo "Setting PROMETHEUS_URLS: $PROMETHEUS_URLS"
fi

# if the influxdb url does not start with a quote, assume it's singular and quote it
if [ "${INFLUXDB_URLS:0:1}" != "\"" ]; then
  export INFLUXDB_URLS="\"$INFLUXDB_URLS\""
fi

echo "Building config.toml!"
envtpl -in config.toml.tpl | sed  '/^$/d' > config.toml

echo "Finished building toml..."
echo "###########################################"
echo "###########################################"
cat config.toml
echo "###########################################"
echo "###########################################"
telegraf -config config.toml -quiet
