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

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

echo "=== Monitoring stack deploy ==="

mkdir -p /mnt/tank/docker/appdata/prometheus
mkdir -p /mnt/tank/docker/appdata/grafana
mkdir -p /mnt/tank/docker/appdata/grafana/dashboards
mkdir -p /mnt/tank/docker/appdata/loki
mkdir -p /mnt/tank/docker/appdata/promtail

chown 65534:65534 /mnt/tank/docker/appdata/prometheus
chown 472:472 /mnt/tank/docker/appdata/grafana
chown 472:472 /mnt/tank/docker/appdata/grafana/dashboards

if [[ ! -f .env ]]; then
  cp .env.example .env
  gf_pass="$(openssl rand -hex 16)"
  sed -i "s/^GF_ADMIN_PASS=CHANGE_ME$/GF_ADMIN_PASS=$gf_pass/" .env
  chmod 600 .env
  echo "Created .env with a random Grafana admin password."
fi

if compgen -G "$SCRIPT_DIR/dashboards/*.json" >/dev/null; then
  cp "$SCRIPT_DIR"/dashboards/*.json /mnt/tank/docker/appdata/grafana/dashboards/
  chown 472:472 /mnt/tank/docker/appdata/grafana/dashboards/*.json
fi

docker compose --env-file .env config >/dev/null
docker compose --env-file .env up -d

echo
docker ps --filter name=prometheus --filter name=grafana --filter name=loki --filter name=promtail --filter name=cadvisor --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
echo
curl -fsS http://127.0.0.1:9090/-/ready >/dev/null && echo "Prometheus ready"
[[ "$(docker inspect -f '{{.State.Running}}' loki 2>/dev/null)" == "true" ]] && echo "Loki running"
curl -fsS http://127.0.0.1:9100/metrics >/dev/null && echo "node-exporter ready"
docker exec cadvisor wget -qO- http://127.0.0.1:8080/metrics >/dev/null 2>&1 && echo "cAdvisor ready" || true
