#!/bin/bash

# k-show-secret: Display Kubernetes secrets interactively or by name
# Usage: k-show-secret [secret-name]  (uses fzf if no name is provided)

# Get the current namespace from the current kubectl context
NAMESPACE=$(kubectl config view --minify --output 'jsonpath={..namespace}')
NAMESPACE=${NAMESPACE:-default}

# If a secret name is passed as argument, use it; otherwise use fzf
if [ -n "$1" ]; then
  SELECTED_SECRET="$1"
else
  # Fetch all secret names in the current namespace
  secrets=$(kubectl get secrets -n "$NAMESPACE" -o jsonpath="{.items[*].metadata.name}")

  if [ -z "$secrets" ]; then
    echo "❌ No secrets found in namespace '$NAMESPACE'."
    exit 1
  fi

  # Use fzf for interactive secret selection
  SELECTED_SECRET=$(echo "$secrets" | tr ' ' '\n' | fzf --prompt="🔐 Select a secret: ")

  # Check if a selection was made
  if [ -z "$SELECTED_SECRET" ]; then
    echo "🚫 No secret selected."
    exit 1
  fi
fi

echo
echo "🔓 Decoding secret '$SELECTED_SECRET' in namespace '$NAMESPACE'..."
echo

# Decode and display the secret data
kubectl get secret "$SELECTED_SECRET" -n "$NAMESPACE" -o json | \
  jq -r '.data | to_entries[] | "\(.key): \(.value | @base64d)"'
