#!/bin/bash

# Set the name of the Kubernetes namespace to deploy to.
K8S_NAMESPACE="tf-dev"
K8S_HOSTNAME="kubernetes-master"

export INFLUXDB_HOSTNAME=$(kubectl get node $K8S_HOSTNAME -o 'jsonpath={.status.addresses[?(@.type=="InternalIP")].address}')
export INFLUXDB_PORT=$(kubectl get service influx-tests --namespace $K8S_NAMESPACE -o 'jsonpath={.spec.ports[?(@.port==8086)].nodePort}')
export INFLUXDB_USER=$(kubectl --namespace $K8S_NAMESPACE get secrets influxdb-secrets -o jsonpath='{.data.INFLUXDB_ADMIN_USER}' | base64 --decode)
export INFLUXDB_PASSWORD=$(kubectl --namespace $K8S_NAMESPACE get secrets influxdb-secrets -o jsonpath='{.data.INFLUXDB_ADMIN_PASSWORD}' | base64 --decode)
export INFLUXDB_DATABASE=$(kubectl --namespace $K8S_NAMESPACE get secrets influxdb-secrets -o jsonpath='{.data.INFLUXDB_DB}' | base64 --decode)
export INFLUXDB_URL="http://${INFLUXDB_HOSTNAME}:${INFLUXDB_PORT}"

export GRAFANA_HOSTNAME=$(kubectl get node $K8S_HOSTNAME -o 'jsonpath={.status.addresses[?(@.type=="InternalIP")].address}')
export GRAFANA_PORT=$(kubectl get service webuiservice-public --namespace $K8S_NAMESPACE -o 'jsonpath={.spec.ports[?(@.port==3000)].nodePort}')
export GRAFANA_USERNAME="admin"
export GRAFANA_PASSWORD="admin123+"
export GRAFANA_URL="http://${GRAFANA_USERNAME}:${GRAFANA_PASSWORD}@${GRAFANA_HOSTNAME}:${GRAFANA_PORT}"

echo ${GRAFANA_URL}/api/datasources

# Create InfluxDB DataSource
# Ref: https://grafana.com/docs/grafana/latest/http_api/data_source/
curl -X POST -H "Content-Type: application/json" -d '{
  "type"     : "influxdb",
  "name"     : "InfluxDB",
  "url"      : "'"$INFLUXDB_URL"'",
  "access"   : "proxy",
  "basicAuth": false,
  "user"     : "'"$INFLUXDB_USER"'",
  "password" : "'"$INFLUXDB_PASSWORD"'",
  "isDefault": true,
  "database" : "'"$INFLUXDB_DATABASE"'"
}' ${GRAFANA_URL}/api/datasources
echo

# Create Monitoring Dashboard
# Ref: https://grafana.com/docs/grafana/latest/http_api/dashboard/
curl -X POST -H "Content-Type: application/json" \
  -d '@src/webui/grafana_dashboard.json' \
  ${GRAFANA_URL}/api/dashboards/db
echo
