#!/bin/bash

# Exit on any error
set -e

# Check if kubectl is available
if ! command -v kubectl >/dev/null 2>&1; then
    echo "Error: kubectl is not installed or not in PATH"
    exit 1
fi

# Check if jq is available
if ! command -v jq >/dev/null 2>&1; then
    echo "Error: jq is not installed or not in PATH"
    exit 1
fi

# Check if fzf is available
if ! command -v fzf >/dev/null 2>&1; then
    echo "Error: fzf is not installed or not in PATH"
    exit 1
fi

# Get the namespace
read -p "Enter namespace (default: sieservice): " NAMESPACE
NAMESPACE=${NAMESPACE:-sieservice}

# List and select secret
echo "Selecting secret from namespace '$NAMESPACE'..."
SECRET=$(kubectl get secret -n "$NAMESPACE" | grep -v 'NAME.*TYPE.*DATA.*AGE' | fzf --height 50% --reverse --header="Select a secret")

if [ -z "$SECRET" ]; then
    echo "No secret selected. Exiting."
    exit 1
fi

# Extract just the secret name from the selection
SECRET_NAME=$(echo "$SECRET" | awk '{print $1}')

# Get and decode the secret
echo "Fetching secret '$SECRET_NAME'..."
DOTENV_CONTENT=$(kubectl get secret "$SECRET_NAME" -n "$NAMESPACE" -o json | \
    jq -r '.data | to_entries | .[] | 
    if (.value | @base64d | startswith("{")) or (.key | endswith(".json")) or (.key | endswith(".key")) or (.key | endswith(".pem")) then
        .value | @base64d
    else
        "\(.key)=\(.value | @base64d)"
    end')

if [ -z "$DOTENV_CONTENT" ]; then
    echo "Error: Failed to extract secret data"
    exit 1
fi

# Preview the content
echo "Secret content preview:"
echo "----------------------------------------"
echo "$DOTENV_CONTENT"
echo "----------------------------------------"

# Get filename and save
read -p "Enter filename to save (or press Ctrl+C to cancel): " filename < /dev/tty

if [ -f "$filename" ]; then
    read -p "File exists. Overwrite? (y/N): " confirm < /dev/tty
    if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
        echo "Operation cancelled."
        exit 0
    fi
fi

echo "$DOTENV_CONTENT" > "$filename"
echo "Secret has been saved to '$filename'"