#!/bin/bash

# Setup Docker Hub image pull secrets for all namespaces
# This script creates docker-registry secrets for pulling images from Docker Hub

set -e

# Docker Hub credentials
DOCKER_SERVER="docker.io"
DOCKER_USERNAME="uals"
DOCKER_PASSWORD="dckr_pat_zzEY5Q58x1S0puraIoKEtbpue3A"
DOCKER_EMAIL="ualfaro@gmail.com"
SECRET_NAME="dockerhub-creds"

# List of namespaces used in the project
NAMESPACES=(
  "bakery-ia"
  "bakery-ia-dev"
  "bakery-ia-prod"
  "default"
)

echo "Setting up Docker Hub image pull secrets..."
echo "==========================================="
echo ""

for namespace in "${NAMESPACES[@]}"; do
  echo "Processing namespace: $namespace"

  # Create namespace if it doesn't exist
  if ! kubectl get namespace "$namespace" >/dev/null 2>&1; then
    echo "  Creating namespace: $namespace"
    kubectl create namespace "$namespace"
  fi

  # Delete existing secret if it exists
  if kubectl get secret "$SECRET_NAME" -n "$namespace" >/dev/null 2>&1; then
    echo "  Deleting existing secret in namespace: $namespace"
    kubectl delete secret "$SECRET_NAME" -n "$namespace"
  fi

  # Create the docker-registry secret
  echo "  Creating Docker Hub secret in namespace: $namespace"
  kubectl create secret docker-registry "$SECRET_NAME" \
    --docker-server="$DOCKER_SERVER" \
    --docker-username="$DOCKER_USERNAME" \
    --docker-password="$DOCKER_PASSWORD" \
    --docker-email="$DOCKER_EMAIL" \
    -n "$namespace"

  echo "  ✓ Secret created successfully in namespace: $namespace"
  echo ""
done

echo "==========================================="
echo "Docker Hub secrets setup completed!"
echo ""
echo "The secret '$SECRET_NAME' has been created in all namespaces:"
for namespace in "${NAMESPACES[@]}"; do
  echo "  - $namespace"
done
echo ""
echo "Next steps:"
echo "1. Apply Kubernetes manifests with imagePullSecrets configured"
echo "2. Verify pods can pull images: kubectl get pods -A"
