#!/bin/sh
#Nifty: Detect services for exporters we support and attempt installs
curl -s https://nifty.sh/lib/universal/niftylib.sh > /tmp/lib.nifty.sh
. /tmp/lib.nifty.sh
rm -f /tmp/lib.nifty.sh

require_root
require_os centos7 alma8 alma9 alma10

if ! yum repoinfo teamblue_saferepo 2> /dev/null | grep -q Repo-id; then
  err "teamblue repo missing"
  exit 1
fi

is_installed() {
  rpm -q --qf "" $1 2> /dev/null
}

# Always this
if ! is_installed teamblue-prometheus-node_exporter; then
  yum install teamblue-prometheus-node_exporter -y
  ce "Installed node exporter!"

  # Check if hidepid is enabled and add the exporter to the superuser group if it is
  # (hidepid is what prevents users from seeing eachother's processes on CloudLinux
  if mount -t "proc" | grep -qF "hidepid=invisible"; then
    ce "Detected CloudLinux or other hidepid configuration"
    SUPERUSER_GID="$(sysctl -n "fs.proc_super_gid")"

    # Sanity check that we actually got the GID
    if [ ! -n "$SUPERUSER_GID" ]; then
      err "Server seems to be using hidepid, but we couldn't get the GID of the supergroup."
      err "Some node metrics may be missing until this is resolved by manually adding tbnexport_node to the relevant group."
    else
      ce "Added tbnexport_node to hidepid supergroup."
      usermod -aG "$SUPERUSER_GID" "tbnexport_node"
    fi
  fi

  systemctl start teamblue-node_exporter
  systemctl enable teamblue-node_exporter
fi

# If anything is listening on 3306 and we can log into it using root/admin
if ss -ntl | grep -qE 'LISTEN.*:3306\s' && ! ss -ntl | grep -qE "LISTEN.*:9104\s"; then
  MYCMD="mysql -uroot -p$(cat /root/.mysql)"
  if [ -f "/root/.mysql" ]; then
    echo "Found .mysql"
    if ! $MYCMD -e "SELECT TRUE" > /dev/null 2>&1; then
      err "Sorry! Cannot log in to MySQL as root"
      MYCMD=
    fi
  elif [ -f "/etc/psa/.psa.shadow" ]; then
    echo "Found .psa.shadow"
    MYCMD="mysql -uadmin -p$(cat /etc/psa/.psa.shadow)"
    if ! $MYCMD -e "SELECT TRUE" > /dev/null 2>&1; then
      err "Sorry! Cannot log in to MySQL as root"
      MYCMD=
    fi
  else
    err "Sorry! Cannot detect a way to log in to mysql. Install MySQL exporter manually"
  fi

  if [ -n "$MYCMD" ]; then
    # Last check: are we a replica?
    $MYCMD -e 'SHOW REPLICA STATUS\G' 2>/dev/null |grep Log_Pos
    if [ "$?" = "0" ]; then
      err "This looks like a replica! I refuse to install the exporter autmatically"
      exit 1
    fi

    EXPORTERPW=$(random_string 16)
    yum install teamblue-prometheus-mysqld_exporter -y
    sed -i "s/password=/password=$EXPORTERPW/" /opt/teamblue/exporters/mysqld_exporter/.my.cnf
    $MYCMD -e "CREATE USER tbnexport_mysqld@127.0.0.1 IDENTIFIED BY '$EXPORTERPW'"
    $MYCMD -e "CREATE USER tbnexport_mysqld@'::1' IDENTIFIED BY '$EXPORTERPW'"
    $MYCMD -e "GRANT PROCESS, REPLICATION CLIENT, SELECT ON *.* TO tbnexport_mysqld@127.0.0.1"
    $MYCMD -e "GRANT PROCESS, REPLICATION CLIENT, SELECT ON *.* TO tbnexport_mysqld@'::1'"
    $MYCMD -e "FLUSH PRIVILEGES"
    systemctl enable teamblue-mysqld_exporter
    systemctl start teamblue-mysqld_exporter

    ce "Installed MySQL exporter!"
    ce "Please test it: curl localhost:9104/metrics | grep innodb"
  fi
fi

if ss -ntl | grep -qE 'LISTEN.*:5432\s' && ! ss -ntl | grep -qE 'LISTEN.*:9187'; then
  yum install -y teamblue-prometheus-postgres_exporter
  PGE_USERNAME="postgres_exporter"
  PGE_PASSWORD="$(random_string 32)"

  mkdir -p /etc/systemd/system/teamblue-postgres_exporter.service.d
  tee /etc/systemd/system/teamblue-postgres_exporter.service.d/override.conf > /dev/null <<EOF
[Service]
EnvironmentFile=-/etc/default/teamblue-postgres_exporter
EOF

  with_umask 077 tee /etc/default/teamblue-postgres_exporter > /dev/null <<EOF
DATA_SOURCE_URI="127.0.0.1:5432/postgres?sslmode=disabled"
DATA_SOURCE_USER="$PGE_USERNAME"
DATA_SOURCE_PASS="$PGE_PASSWORD"
EOF

  psql -qc "CREATE USER $PGE_USERNAME WITH ENCRYPTED PASSWORD '$PGE_PASSWORD'"
  psql -qc "GRANT pg_monitor, pg_read_all_stats TO $PGE_USERNAME"

  systemctl daemon-reload
  systemctl enable teamblue-postgres_exporter
  systemctl start teamblue-postgres_exporter
  sleep 1

  if curl -Ss '127.0.0.1:9187/metrics' | grep -qE '^pg_up\s+1'; then
    ce "PostgreSQL exporter installed and running!"
  else
    err "PostgreSQL exporter is reporting PostgreSQL as down:"
    SYSTEMD_PAGER="" journalctl -u teamblue-postgres_exporter -n 5
    echo
  fi
fi

# If anything is listening on 3306 and we can log into it using root/admin
if ss -ntl | grep -qE 'LISTEN.*:6379\s' && ! ss -ntl | grep -qE 'LISTEN.*:9121\s'; then
  echo "Something is listening on 6379"
  yum install teamblue-prometheus-redis_exporter -y
  systemctl enable teamblue-redis_exporter
  systemctl start teamblue-redis_exporter
  sleep 1

  if [ "$(curl -s localhost:9121/metrics |grep -E '^redis_up ' |awk '{print $2}')" != "1" ]; then
    err "redis_up is not 1! Find out why."
    echo "Try localhost:9121/metrics"
    echo "Try grep redis_exporter /var/log/messages"
    echo "Might be requirepass - if so, create an override file."
  else
    ce "Redis exporter installed"
  fi
fi


if ss -ntlp | grep -qE 'LISTEN.*varnishd' && ! ss -ntl | grep -qE 'LISTEN.*:9121\s'; then
    echo "varnish is listening"
    yum install teamblue-prometheus-varnish_exporter -y
    usermod -a -G varnish tbnexport_varnish
    systemctl enable teamblue-varnish_exporter
    systemctl start teamblue-varnish_exporter
    sleep 1
    if [ "$(curl -s localhost:9131/metrics |grep -E '^varnish_up ' |awk '{print $2}')" != "1" ]; then
      err "varnish_up is not 1! Find out why."
    else
      ce "Varnish exporter installed"
    fi
 fi
