#!/bin/bash
# Generate and deploy Django secret key to Kubernetes

NAMESPACE="vorgabenui"
SECRET_NAME="django-secret"
SECRET_FILE="templates/secret.yaml"

# Check if secret file exists
if [ ! -f "$SECRET_FILE" ]; then
    echo "Error: $SECRET_FILE not found"
    exit 1
fi

# Generate random secret key
SECRET_KEY=$(python3 -c "import secrets; print(secrets.token_urlsafe(50))")

# Create temporary secret file with generated key
TEMP_SECRET_FILE=$(mktemp)
cat "$SECRET_FILE" | sed "s/CHANGE_ME_TO_RANDOM_STRING/$SECRET_KEY/g" > "$TEMP_SECRET_FILE"

# Check if secret already exists
if kubectl get secret "$SECRET_NAME" -n "$NAMESPACE" &>/dev/null; then
    echo "Secret $SECRET_NAME already exists in namespace $NAMESPACE"
    read -p "Do you want to replace it? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "Aborted"
        rm "$TEMP_SECRET_FILE"
        exit 0
    fi
    kubectl apply -f "$TEMP_SECRET_FILE"
    echo "Secret updated successfully"
else
    kubectl apply -f "$TEMP_SECRET_FILE"
    echo "Secret created successfully"
fi

# Clean up
rm "$TEMP_SECRET_FILE"

echo ""
echo "Secret deployed:"
echo "  Name: $SECRET_NAME"
echo "  Namespace: $NAMESPACE"
echo "  Key: secret-key"
