#!/usr/bin/env bash
set -euo pipefail

sudo apt-get update
sudo apt-get install -y prometheus prometheus-node-exporter jq curl apt-transport-https software-properties-common wget

sudo sed -i 's/^ARGS=.*/ARGS="--web.listen-address=127.0.0.1:9100 --collector.textfile.directory=\\/var\\/lib\\/prometheus\\/node-exporter-textfile"/' /etc/default/prometheus-node-exporter
sudo install -d -o prometheus -g prometheus -m 755 /var/lib/prometheus/node-exporter-textfile

sudo install -d -m 755 /etc/prometheus/rules

echo "Copy prometheus-example.yml to /etc/prometheus/prometheus.yml"
echo "Copy monad-alerts-example.yml to /etc/prometheus/rules/monad-alerts.yml"
echo "Copy monad-export-metrics-example.sh to /usr/local/bin/monad-export-metrics"

sudo tee /etc/systemd/system/monad-health-exporter.service >/dev/null <<'EOF'
[Unit]
Description=Export Monad custom health metrics for Prometheus textfile collector

[Service]
Type=oneshot
ExecStart=/usr/local/bin/monad-export-metrics
EOF

sudo tee /etc/systemd/system/monad-health-exporter.timer >/dev/null <<'EOF'
[Unit]
Description=Run Monad health exporter every minute

[Timer]
OnBootSec=30s
OnUnitActiveSec=60s
Unit=monad-health-exporter.service

[Install]
WantedBy=timers.target
EOF

sudo systemctl daemon-reload
sudo systemctl enable --now prometheus prometheus-node-exporter monad-health-exporter.timer
sudo systemctl start monad-health-exporter.service

wget -q -O - https://apt.grafana.com/gpg.key | sudo gpg --dearmor -o /usr/share/keyrings/grafana.gpg
echo "deb [signed-by=/usr/share/keyrings/grafana.gpg] https://apt.grafana.com stable main" | sudo tee /etc/apt/sources.list.d/grafana.list
sudo apt-get update
sudo apt-get install -y grafana
sudo perl -0pi -e 's/;http_addr =/http_addr = 0.0.0.0/; s/;http_port = 3000/http_port = 3000/' /etc/grafana/grafana.ini
sudo systemctl enable --now grafana-server

sudo promtool check config /etc/prometheus/prometheus.yml
sudo systemctl restart prometheus

echo "Next step: configure Grafana Telegram contact point and notification policy."
