#!/bin/bash
#Nifty: Install Prometheus MySQLd Exporter and set up MySQL

curl -s https://nifty.sh/lib/universal/niftylib.sh > /tmp/lib.nifty.sh
. /tmp/lib.nifty.sh
rm -f /tmp/lib.nifty.sh

# Requirements
require_root
require_64bit
require_os centos7


randpw(){ < /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c${1:-16};echo;}

yum install -y teamblue-prometheus-mysqld_exporter.x86_64

# Detect mysql credentials
ce "Detecting MySQL credentials"
if [ -f "/etc/psa/.psa.shadow" ]; then
        MYSQLPW=`cat /etc/psa/.psa.shadow`
        MYSQLUSER="admin"
elif [ -f "/root/.mysql" ]; then
        MYSQLPW=`cat /root/.mysql`
        MYSQLUSER="root"
else
        err "Could not determine mysql credentials"
        exit 1
fi
ce "Got MySQL credentials"

ce "Testing MySQL credentials"
mysql -e "SHOW DATABASES;" -u${MYSQLUSER} -p${MYSQLPW} > /dev/null 2>&1

if [ "$?" -gt "0" ]; then
        err "Could not log in to mysql"
        exit 1
fi
ce "Logged in to MySQL"

ce "Creating tbnexport_mysqld user in MySQL"
PW=$(randpw)
mysql -u${MYSQLUSER} -p${MYSQLPW} -e "CREATE USER 'tbnexport_mysqld'@'127.0.0.1' IDENTIFIED BY '$PW';"
mysql -u${MYSQLUSER} -p${MYSQLPW} -e "GRANT PROCESS, REPLICATION CLIENT, SELECT ON *.* TO 'tbnexport_mysqld'@'127.0.0.1';"
mysql -u${MYSQLUSER} -p${MYSQLPW} -e "FLUSH PRIVILEGES;"


ce "Setting up exporter config"
sed -i "s/password=/password=$PW/" /opt/teamblue/exporters/mysqld_exporter/.my.cnf

ce "Enabling exporter"
systemctl enable teamblue-mysqld_exporter
systemctl stop teamblue-mysqld_exporter
systemctl start teamblue-mysqld_exporter

ce "Waiting 2 seconds for it to become ready"
sleep 2

curl http://localhost:9104/metrics

ce ""
ce ""
ce "Be sure to check above if it has mysql data"
ce ""
ce ""
