#!/bin/bash

# Script: get_grafana_password.sh
# Description: Retrieves the Grafana admin password from its Kubernetes Secret.
# Usage: ./get_grafana_password.sh [namespace] [secret_name]

# --- Configuration (can be overridden by command-line arguments) ---
GRAFANA_NAMESPACE="${1:-monitoring}"      # Default to 'monitoring'
GRAFANA_SECRET_NAME="${2:-monitoring-grafana}" # Default to 'monitoring-grafana'

# --- Main Logic ---

echo "Attempting to retrieve Grafana admin password from secret '$GRAFANA_SECRET_NAME' in namespace '$GRAFANA_NAMESPACE'..."

# Retrieve and decode the password. `2>/dev/null` suppresses kubectl errors.
GRAFANA_PASSWORD=$(kubectl get secret -n "$GRAFANA_NAMESPACE" "$GRAFANA_SECRET_NAME" -o jsonpath="{.data.admin-password}" 2>/dev/null | base64 --decode 2>/dev/null)

if [ -z "$GRAFANA_PASSWORD" ]; then
    echo "Error: Could not retrieve Grafana admin password."
    echo "Possible reasons:"
    echo "  - Secret '$GRAFANA_SECRET_NAME' not found in namespace '$GRAFANA_NAMESPACE'."
    echo "  - The key 'admin-password' is missing within the secret."
    echo "  - kubectl permissions are insufficient."
    echo "  - The secret or key names are incorrect. Verify with 'kubectl get secret -n $GRAFANA_NAMESPACE $GRAFANA_SECRET_NAME -o yaml'."
    exit 1
fi

echo "Grafana Admin Password: $GRAFANA_PASSWORD"
