#!/usr/bin/env bash

set -e

BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Install Grafana dependencies
sudo apt-get install libfontconfig1 fontconfig-config fonts-dejavu-core ttf-bitstream-vera fonts-liberation sqlite3 -y

# Download and install unofficial build of Grafana for ARM
URL="https://bintray.com/fg2it/deb/download_file?file_path=main%2Fg%2Fgrafana_4.3.2_armhf.deb"
if $(uname -m | grep -Eq ^armv6); then
    URL="https://bintray.com/fg2it/deb-rpi-1b/download_file?file_path=main%2Fg%2Fgrafana_4.3.2_armhf.deb"
fi
mkdir "$BASE_DIR/tmp"
wget ${URL} -O "$BASE_DIR/tmp/go-grafana.tar.gz"
sudo dpkg -i "$BASE_DIR/tmp/go-grafana.tar.gz"
rm -rf "$BASE_DIR/tmp"

# Configure systemd to start grafana-server.service on system boot
sudo systemctl daemon-reload
sudo systemctl enable grafana-server.service
sudo systemctl start grafana-server.service

# Wait for server to start
sleep 30

# Add data source and dashboard
curl --user admin:admin -X POST -H 'Content-Type: application/json' --data-binary @$BASE_DIR/datasource.json http://localhost:3000/api/datasources
curl --user admin:admin -X POST -H 'Content-Type: application/json' --data-binary @$BASE_DIR/dashboard.json http://localhost:3000/api/dashboards/db
