#!/bin/bash

# Source variables from user-data
. /etc/teleport.d/conf

# Enable/start grafana
systemctl enable grafana-server
systemctl start grafana-server

# Enable/start influxdb
systemctl enable influxdb.service
systemctl restart influxdb.service

# Import dashboard and data source
until $(curl --output /dev/null --silent --head --fail http://localhost:3000); do
    echo "waiting for grafana to respond"
    sleep 5
done

echo "Grafana is up setting up dashboards and data sources"

GRAFANA_PASS="$(aws ssm get-parameter --with-decryption --name /teleport/${TELEPORT_CLUSTER_NAME}/grafana_pass --region ${EC2_REGION} --query 'Parameter.Value' --output text)"

# if the password hasn't been changed from the default, set it to a random value (for security) and then also write that
# parameter back to SSM so the user can find out what it is
if [[ "${GRAFANA_PASS}" == "CHANGE_THIS_VALUE" ]]; then
    GRAFANA_PASS=$(hexdump -n 16 -e '4/4 "%08X" 1 "\n"' /dev/urandom)
    aws ssm put-parameter --name /teleport/${TELEPORT_CLUSTER_NAME}/grafana_pass --region ${EC2_REGION} --value "${GRAFANA_PASS}" --type SecureString --overwrite
    echo "Grafana password has been set to ${GRAFANA_PASS} as it wasn't changed from the default CHANGE_THIS_VALUE"
fi

# Change grafana password
curl -X PUT -u admin:admin -H 'Content-Type: application/json' -d "{
  \"oldPassword\": \"admin\",
  \"newPassword\": \"${GRAFANA_PASS}\",
  \"confirmNew\": \"${GRAFANA_PASS}\"
}" http://127.0.0.1:3000/api/user/password

# Set up default input
curl -s -H "Content-Type: application/json" \
    -XPOST -u admin:${GRAFANA_PASS} http://127.0.0.1:3000/api/datasources \
    -d @- <<EOF
{
    "name": "InfluxDB",
    "type": "influxdb",
    "access": "proxy",
    "url": "http://127.0.0.1:8086",
    "database": "telegraf"
}
EOF

# Download and setup teleport dashboard
aws s3 --region=${EC2_REGION} cp s3://${TELEPORT_S3_BUCKET}/health-dashboard.json /tmp/health-dashboard.json
curl -X POST -u admin:${GRAFANA_PASS} -H 'Content-Type: application/json' -d @/tmp/health-dashboard.json http://127.0.0.1:3000/api/dashboards/db
# Star dashboard
curl -X POST -u admin:${GRAFANA_PASS} -H 'X-Grafana-Org-Id: 1' http://127.0.0.1:3000/api/user/stars/dashboard/1
# Set home/default dashboard
curl -X PUT -u admin:${GRAFANA_PASS} -H 'X-Grafana-Org-Id: 1' -H 'Content-Type: application/json' -d "{
  \"theme\": \"\",
  \"homeDashboardId\":1,
  \"timezone\":\"utc\"
}" http://127.0.0.1:3000/api/org/preferences

# Setup nginx frontend for grafana
mkdir -p /etc/tls/certs
cat >/lib/systemd/system/nginx.service <<EOF
[Unit]
Description=A high performance web server and a reverse proxy server
Documentation=man:nginx(8)
After=network.target

[Service]
Restart=always
RestartSec=5
Type=forking
PIDFile=/run/nginx.pid
ExecStartPre=/bin/aws s3 sync s3://${TELEPORT_S3_BUCKET}/live/${TELEPORT_DOMAIN_NAME} /etc/tls/certs
ExecStartPre=/usr/sbin/nginx -t -q -g 'daemon on; master_process on;'
ExecStart=/usr/sbin/nginx -g 'daemon on; master_process on;'
ExecReload=/usr/sbin/nginx -g 'daemon on; master_process on;' -s reload
ExecStop=-/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid
TimeoutStopSec=5
KillMode=mixed

[Install]
WantedBy=multi-user.target
EOF

# Update nginx configuration to use TLS and frontend grafana and restart nginx
aws s3 --region=${EC2_REGION} cp s3://${TELEPORT_S3_BUCKET}/grafana-nginx.conf /etc/nginx/nginx.conf
systemctl daemon-reload
systemctl restart nginx --no-block