#!/bin/bash

exit 0

echo 'deb http://packagecloud.io/grafana/stable/debian/ stretch main' >> /etc/apt/sources.list

curl https://packagecloud.io/gpg.key | sudo apt-key add -

apt update
apt-get -y install apt install grafana

systemctl daemon-reload
systemctl enable grafana-server
systemctl start grafana-server

# Set up pen
# To run manually:
apt-get -y install pen mariadb-client
useradd pen
echo "d /var/run/pen 0755 pen pen -" > /etc/tmpfiles.d/pen.conf
systemd-tmpfiles --create

mkdir -p /etc/pen
cat > /etc/pen/galera.cfg <<EOF
server 0 address 10.42.1.171 port 3306
server 2 address 10.42.1.172 port 3306
server 3 address 10.42.1.173 port 3306
server 4 address 10.42.1.174 port 3306
debug 1
EOF

cat > /lib/systemd/system/pen-galera.service <<EOF
[Unit]
Description=Pen load balancer (galera)
After=network.target

[Service]
User=pen
Type=forking
PIDFile=/var/run/pen/galera.pid
ExecStart=/usr/bin/pen -u pen -C /var/run/pen/galera.ctl -F /etc/pen/galera.cfg -p /var/run/pen/galera.pid 127.0.0.1:3306
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

systemctl restart pen-galera
systemctl enable pen-galera.service

# Set up mysql
# In database, to store grafana data:
CREATE DATABASE grafana CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
CREATE USER 'grafana'@'10.42.1.111' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON grafana.* TO 'grafana'@'10.42.1.111';
FLUSH PRIVILEGES;

# Create database for grafana to poll mysql:
CREATE USER 'grafanaReader'@'10.42.1.111' IDENTIFIED BY 'password';
GRANT SELECT ON grafana.* TO 'grafanaReader'@'10.42.1.111';
FLUSH PRIVILEGES;

