#!/bin/bash

# =============================================================================
# Create Docker Hub Image Pull Secret
# =============================================================================
# This script creates a Kubernetes secret for pulling images from Docker Hub.
# The secret is used by both:
# 1. bakery-ia namespace deployments (Tilt + Kustomize)
# 2. Signoz Helm deployment
#
# Usage:
#   ./create-dockerhub-secret.sh
#
# Prerequisites:
#   - kubectl configured with access to the cluster
#   - DOCKERHUB_USERNAME and DOCKERHUB_PASSWORD environment variables set
#   - OR Docker CLI logged in (docker login)
# =============================================================================

set -e

echo "🔐 Creating Docker Hub Image Pull Secret"
echo "=========================================="
echo ""

# Check for required environment variables
if [ -z "$DOCKERHUB_USERNAME" ] || [ -z "$DOCKERHUB_PASSWORD" ]; then
    echo "⚠️  DOCKERHUB_USERNAME and DOCKERHUB_PASSWORD environment variables not set"
    echo ""
    echo "Checking if Docker CLI is logged in..."

    # Try to extract credentials from Docker config
    if [ -f "$HOME/.docker/config.json" ]; then
        # Check if using credential store
        if grep -q "credsStore" "$HOME/.docker/config.json"; then
            echo "⚠️  Docker is using a credential store. Please set environment variables manually:"
            echo ""
            echo "  export DOCKERHUB_USERNAME='your-username'"
            echo "  export DOCKERHUB_PASSWORD='your-password-or-token'"
            echo ""
            exit 1
        fi

        # Try to extract from base64 encoded auth
        AUTH=$(cat "$HOME/.docker/config.json" | jq -r '.auths["https://index.docker.io/v1/"].auth // empty' 2>/dev/null)
        if [ -n "$AUTH" ]; then
            echo "✅ Found Docker Hub credentials in Docker config"
            DOCKERHUB_USERNAME=$(echo "$AUTH" | base64 -d | cut -d: -f1)
            DOCKERHUB_PASSWORD=$(echo "$AUTH" | base64 -d | cut -d: -f2-)
        else
            echo "❌ Could not find Docker Hub credentials"
            echo ""
            echo "Please either:"
            echo "  1. Run 'docker login' first, OR"
            echo "  2. Set environment variables:"
            echo "     export DOCKERHUB_USERNAME='your-username'"
            echo "     export DOCKERHUB_PASSWORD='your-password-or-token'"
            echo ""
            exit 1
        fi
    else
        echo "❌ Docker config not found and environment variables not set"
        echo ""
        echo "Please set environment variables:"
        echo "  export DOCKERHUB_USERNAME='your-username'"
        echo "  export DOCKERHUB_PASSWORD='your-password-or-token'"
        echo ""
        exit 1
    fi
fi

echo "Using Docker Hub username: $DOCKERHUB_USERNAME"
echo ""

# Function to create secret in a namespace
create_secret_in_namespace() {
    local NAMESPACE=$1

    echo "📦 Creating secret in namespace: $NAMESPACE"

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

    # Delete existing secret if it exists
    if kubectl get secret dockerhub-creds -n "$NAMESPACE" &>/dev/null; then
        echo "  Deleting existing secret..."
        kubectl delete secret dockerhub-creds -n "$NAMESPACE"
    fi

    # Create the secret
    kubectl create secret docker-registry dockerhub-creds \
        --docker-server=https://index.docker.io/v1/ \
        --docker-username="$DOCKERHUB_USERNAME" \
        --docker-password="$DOCKERHUB_PASSWORD" \
        --docker-email="${DOCKERHUB_EMAIL:-noreply@bakery-ia.local}" \
        -n "$NAMESPACE"

    echo "  ✅ Secret created successfully"
    echo ""
}

# Create secret in bakery-ia namespace (for Tilt deployments)
create_secret_in_namespace "bakery-ia"

# Create secret in signoz namespace (for Signoz Helm deployment - if namespace exists)
if kubectl get namespace signoz &>/dev/null; then
    create_secret_in_namespace "signoz"
else
    echo "ℹ️  Signoz namespace not found, skipping (will be created on Helm install)"
    echo ""
fi

echo "✅ Docker Hub secrets created successfully!"
echo ""
echo "The secret 'dockerhub-creds' is now available in:"
echo "  - bakery-ia namespace (for Tilt/Kustomize deployments)"
if kubectl get namespace signoz &>/dev/null; then
    echo "  - signoz namespace (for Signoz Helm deployment)"
fi
echo ""
echo "All pods with imagePullSecrets: dockerhub-creds will now use these credentials"
echo "to pull images from Docker Hub."
echo ""
