#!/bin/bash

# Check if at least secret and namespaces are provided
if [ $# -lt 1 ]; then
  echo "Usage: $0 <source-namespace:secret-name> [namespace1 namespace2 ...]"
  exit 1
fi

# Parse secret and namespace
SOURCE_INPUT="$1"
shift

# Split source input into namespace and secret name
IFS=":" read -r SOURCE_NAMESPACE SECRET_NAME <<< "$SOURCE_INPUT"

if [ -z "$SOURCE_NAMESPACE" ] || [ -z "$SECRET_NAME" ]; then
  echo "Error: Source must be in format namespace:secret-name"
  exit 1
fi

# Collect target namespaces
if [ $# -gt 0 ]; then
  NAMESPACES=("$@")
else
  echo "Enter target namespaces (space-separated), then press Ctrl+D:"
  read -a NAMESPACES
fi

for ns in "${NAMESPACES[@]}"; do
  echo "Copying secret '$SECRET_NAME' from namespace '$SOURCE_NAMESPACE' to namespace: '$ns'"

  # Delete the existing secret if it exists
  kubectl delete secret "$SECRET_NAME" -n "$ns" --ignore-not-found

  # Get the secret YAML, change the namespace, and apply it
  kubectl get secret "$SECRET_NAME" -n "$SOURCE_NAMESPACE" -o yaml \
    | sed "s/namespace: $SOURCE_NAMESPACE/namespace: $ns/" \
    | kubectl apply -n "$ns" -f -
done

echo "✅ Secret '$SECRET_NAME' copied successfully."
