#!/usr/bin/env sh
set -eu

# On-demand Prometheus + Grafana for the running pg_exporter devcontainer.
#
# The observability services live in .devcontainer/compose.yaml behind the
# "observability" profile, so a plain `devpod up` (app + postgres only) stays lean.
# This script attaches them to the SAME compose network DevPod created, so
# Prometheus scrapes the exporter by service name (app:9432) with no host
# networking — identical on macOS / Linux / Atomic.
#
# Run the exporter inside the app container first so app:9432 is up (e.g. `just watch`).
#
# Usage: scripts/metrics-dev [up|down]

action="${1:-up}"

cmd="${PG_EXPORTER_CONTAINER_CMD:-}"
if [ -z "$cmd" ]; then
    if command -v podman >/dev/null 2>&1; then
        cmd=podman
    else
        cmd=docker
    fi
fi

project_dir="$(
    unset CDPATH
    cd -- "$(dirname -- "$0")/.." && pwd
)"
compose_file="$project_dir/.devcontainer/compose.yaml"

# DevPod overrides the compose `name:` with its own project, so discover the real
# project name from the running `app` container (named <project>-app-1).
app_ctr="$("$cmd" ps --format '{{.Names}}' 2>/dev/null | grep -E -- '-app-1$' | head -1 || true)"
if [ -z "$app_ctr" ]; then
    echo "Error: devcontainer 'app' container not running." >&2
    echo "Start the workspace first:  ./scripts/dev-up" >&2
    exit 1
fi
project="${app_ctr%-app-1}"

case "$action" in
up)
    echo "Using compose project: $project"
    "$cmd" compose -p "$project" -f "$compose_file" --profile observability up -d prometheus grafana
    echo ""
    echo "  Grafana:    http://localhost:3000   (anonymous admin)"
    echo "  Prometheus: http://localhost:9090"
    echo ""
    echo "  Prometheus scrapes app:9432 over the compose network. Run the exporter"
    echo "  inside the app container so it has data to scrape:  just watch"
    echo "  Edits to grafana/dashboard.json hot-reload in Grafana within ~10s."
    ;;
down | stop)
    echo "Using compose project: $project"
    "$cmd" compose -p "$project" -f "$compose_file" --profile observability stop prometheus grafana
    ;;
*)
    echo "usage: $0 [up|down]" >&2
    exit 1
    ;;
esac
