#!/bin/bash

# Set the name of the Kubernetes namespace to deploy to.
K8S_NAMESPACE="tf-dev"
# gets the first node name in the list
K8S_HOSTNAME=`kubectl get nodes | cut -f1 -d" " | sed -n '2 p'`

export INFLUXDB_HOSTNAME=$(kubectl get node $K8S_HOSTNAME --namespace $K8S_NAMESPACE -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 --namespace $K8S_NAMESPACE -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 -H "Content-Type: application/json" -d '{
  "type"     : "influxdb",bbbbb
  "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 -H "Content-Type: application/json" \
  -d '@src/webui/grafana_dashboard.json' \
  ${GRAFANA_URL}/api/dashboards/db
echo
