#!/bin/bash
# 실습 #19 ② — Grafana 설치 + Prometheus 데이터소스 + 대시보드 1860 import
# - 대시보드 1860 "Node Exporter Full" = 70+ 패널, 95% 케이스 커버
# - data source provisioning + dashboard provisioning 으로 코드화
set -e

DIR="$(cd "$(dirname "$0")" && pwd)"

# 1) 저장소 추가 + 설치
if ! command -v grafana-server >/dev/null; then
    sudo apt install -y software-properties-common
    sudo wget -q -O /usr/share/keyrings/grafana.key https://apt.grafana.com/gpg.key
    echo "deb [signed-by=/usr/share/keyrings/grafana.key] https://apt.grafana.com stable main" | \
        sudo tee /etc/apt/sources.list.d/grafana.list >/dev/null
    sudo apt update
    sudo apt install -y grafana
fi

# 2) data source provisioning — Prometheus 자동 등록
sudo mkdir -p /etc/grafana/provisioning/datasources
sudo cp "$DIR/configs/02_grafana_datasource.yml" /etc/grafana/provisioning/datasources/prometheus.yaml

# 3) dashboard provisioning — 1860 import
sudo mkdir -p /etc/grafana/provisioning/dashboards /var/lib/grafana/dashboards
sudo cp "$DIR/configs/02_grafana_dashboard_provider.yml" /etc/grafana/provisioning/dashboards/lab.yaml

# 4) 1860 JSON 다운로드 (인터넷 필요)
if [ ! -s /var/lib/grafana/dashboards/node_exporter_full.json ]; then
    sudo curl -fsSL -o /var/lib/grafana/dashboards/node_exporter_full.json \
        "https://grafana.com/api/dashboards/1860/revisions/37/download" || \
    sudo curl -fsSL -o /var/lib/grafana/dashboards/node_exporter_full.json \
        "https://grafana.com/api/dashboards/1860/revisions/latest/download"
fi
sudo chown -R grafana:grafana /var/lib/grafana/dashboards /etc/grafana/provisioning

# 5) 시작
sudo systemctl enable --now grafana-server
sleep 5

# 6) 검증
echo
echo "=== grafana-server 상태 ==="
sudo systemctl is-active grafana-server

echo
echo "=== /api/health ==="
curl -s http://localhost:3000/api/health | python3 -m json.tool

echo
echo "=== datasource 등록 확인 (admin/admin) ==="
curl -s -u admin:admin http://localhost:3000/api/datasources | python3 -m json.tool | head -30

cat <<EOF

웹 UI:
  http://<VM-IP>:3000
    초기 계정: admin / admin (첫 로그인 후 비번 변경 요청)
    Dashboards → Node Exporter Full (이미 import 됨)

수동 import 가 필요한 경우:
  Dashboards → New → Import → 1860 → Load → Prometheus 선택
EOF
