#!/bin/bash

# Script: exec_grafana_pod.sh
# Description: Finds the Grafana pod and opens a bash shell inside it.
# Usage: ./exec_grafana_pod.sh [namespace]

# --- Configuration (can be overridden by command-line argument) ---
GRAFANA_NAMESPACE="${1:-monitoring}" # Default to 'monitoring' if no argument provided

# --- Main Logic ---

echo "Searching for Grafana pod in namespace '$GRAFANA_NAMESPACE'..."

# Find the Grafana pod name. Use `head -n 1` in case multiple pods match.
GRAFANA_POD=$(kubectl get pods -n "$GRAFANA_NAMESPACE" -l app.kubernetes.io/name=grafana -o jsonpath='{.items[0].metadata.name}' 2>/dev/null)

if [ -z "$GRAFANA_POD" ]; then
    echo "Error: Grafana pod not found in namespace '$GRAFANA_NAMESPACE'."
    echo "Please ensure Grafana is deployed and running, and the namespace is correct."
    exit 1
fi

echo "Found Grafana pod: $GRAFANA_POD"
echo "--- Executing bash shell into Grafana pod ---"
echo "Type 'exit' to return to your local shell."

# Execute bash shell into the pod.
kubectl exec -it -n "$GRAFANA_NAMESPACE" "$GRAFANA_POD" -- bash

if [ $? -ne 0 ]; then
    echo "Error: Could not exec into pod '$GRAFANA_POD'."
    echo "Check kubectl permissions, if the pod is running, or if 'bash' is available in the container."
    echo "You might try 'sh' instead of 'bash' if bash is not present: kubectl exec -it -n $GRAFANA_NAMESPACE $GRAFANA_POD -- sh"
    exit 1
fi

echo "Exited Grafana pod shell."
