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

ROOT="$(
  git rev-parse --show-toplevel 2>/dev/null || {
    cd "$(dirname "${BASH_SOURCE[0]}")/.."
    pwd
  }
)"

work_dir="${BURROW_GRAFANA_TOFU_DIR:-$ROOT/infra/grafana}"
plugin_cache_dir="${BURROW_TOFU_PLUGIN_CACHE_DIR:-$ROOT/.cache/opentofu/plugins}"

usage() {
  cat <<'EOF'
Usage: Scripts/grafana-tofu.sh [tofu args...]

Runs OpenTofu for Burrow Grafana API configuration. This stack creates folders
and dashboards only; Nix owns the Grafana service, authentication, data sources,
and boot-time provisioning files.

Examples:
  Scripts/grafana-tofu.sh init -backend-config=backend.hcl
  Scripts/grafana-tofu.sh plan -var-file=terraform.tfvars

Local syntax check:
  Scripts/grafana-tofu.sh init -backend=false
  Scripts/grafana-tofu.sh validate
EOF
}

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
  usage
  exit 0
fi

mkdir -p "$plugin_cache_dir"
export TF_PLUGIN_CACHE_DIR="$plugin_cache_dir"
export TF_IN_AUTOMATION="${TF_IN_AUTOMATION:-true}"

exec nix shell --inputs-from "$ROOT" nixpkgs#opentofu -c tofu -chdir="$work_dir" "$@"
