#!/bin/bash
# 실습 #19 ① — Prometheus + node_exporter 기본 설치 + 첫 쿼리
# - node_exporter (9100): OS 메트릭 (CPU/Mem/Disk/Net/FS) 노출
# - Prometheus     (9090): 15초마다 pull 해서 TSDB 에 적재
# - 본 시나리오는 단일 머신 (localhost) 기준. 다중 타겟은 setup_04 에서.
set -e

DIR="$(cd "$(dirname "$0")" && pwd)"
NODE_VER="1.8.2"
PROM_VER="2.55.1"

# 1) prometheus 시스템 사용자
sudo useradd --no-create-home --shell /usr/sbin/nologin prometheus 2>/dev/null || true

# 2) node_exporter
if [ ! -x /usr/local/bin/node_exporter ]; then
    cd /tmp
    wget -q "https://github.com/prometheus/node_exporter/releases/download/v${NODE_VER}/node_exporter-${NODE_VER}.linux-amd64.tar.gz"
    tar xzf "node_exporter-${NODE_VER}.linux-amd64.tar.gz"
    sudo install -m 755 "node_exporter-${NODE_VER}.linux-amd64/node_exporter" /usr/local/bin/
fi

# 3) systemd 서비스 (configs 의 unit 파일)
sudo cp "$DIR/configs/01_node_exporter.service" /etc/systemd/system/node_exporter.service
sudo systemctl daemon-reload
sudo systemctl enable --now node_exporter
sleep 1

# 4) node_exporter 검증
echo "=== node_exporter 메트릭 (앞 3 줄) ==="
curl -s http://localhost:9100/metrics | grep -E "^node_cpu_seconds_total" | head -3

# 5) Prometheus 설치
if [ ! -x /usr/local/bin/prometheus ]; then
    cd /tmp
    wget -q "https://github.com/prometheus/prometheus/releases/download/v${PROM_VER}/prometheus-${PROM_VER}.linux-amd64.tar.gz"
    tar xzf "prometheus-${PROM_VER}.linux-amd64.tar.gz"
    sudo install -m 755 "prometheus-${PROM_VER}.linux-amd64/prometheus"  /usr/local/bin/
    sudo install -m 755 "prometheus-${PROM_VER}.linux-amd64/promtool"    /usr/local/bin/
    sudo mkdir -p /etc/prometheus /var/lib/prometheus
    sudo cp -r "prometheus-${PROM_VER}.linux-amd64/consoles" /etc/prometheus/
    sudo cp -r "prometheus-${PROM_VER}.linux-amd64/console_libraries" /etc/prometheus/
    sudo chown -R prometheus:prometheus /etc/prometheus /var/lib/prometheus
fi

# 6) prometheus.yml + systemd unit
sudo cp "$DIR/configs/01_prometheus.yml" /etc/prometheus/prometheus.yml
sudo cp "$DIR/configs/01_prometheus.service" /etc/systemd/system/prometheus.service
sudo chown -R prometheus:prometheus /etc/prometheus

sudo systemctl daemon-reload
sudo systemctl enable --now prometheus
sleep 3

# 7) 동작 확인
echo
echo "=== prometheus / node_exporter 상태 ==="
sudo systemctl is-active prometheus node_exporter

echo
echo "=== Target up 상태 (API 쿼리) ==="
curl -s 'http://localhost:9090/api/v1/query?query=up' | python3 -m json.tool | head -30

echo
echo "=== PromQL 한 줄 — CPU 사용률 ==="
curl -s --data-urlencode 'query=100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[1m])) * 100)' \
    http://localhost:9090/api/v1/query | python3 -m json.tool

cat <<EOF

웹 UI:
  Prometheus  : http://<VM-IP>:9090
                Status → Targets → 모두 UP 확인
  node_exporter: http://<VM-IP>:9100/metrics

다음:
  setup_02_grafana.sh        — Grafana + 대시보드 1860 import
  setup_03_alertmanager.sh   — Alertmanager + HighCPU 룰
  setup_04_scrape_config.sh  — 다중 타겟 + file_sd
EOF
