#!/bin/bash

# deploy-argocd-configmap.sh
# Script to deploy Django ConfigMap to vorgabenui namespace for ArgoCD

set -euo pipefail

# ArgoCD-specific configuration (hardcoded for consistency)
NAMESPACE="vorgabenui"
CONFIGMAP_NAME="django-config"
SCRIPT_DIR="$(dirname "$0")"
ARGOCD_DIR="$SCRIPT_DIR/../argocd"
CONFIGMAP_FILE="$ARGOCD_DIR/configmap.yaml"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Logging functions
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# Function to check if kubectl is available
check_kubectl() {
    if ! command -v kubectl &> /dev/null; then
        log_error "kubectl is not installed or not in PATH"
        exit 1
    fi
}

# Function to check if configmap file exists
check_configmap_file() {
    if [ ! -f "$CONFIGMAP_FILE" ]; then
        log_error "ConfigMap file not found: $CONFIGMAP_FILE"
        log_error "Expected ArgoCD ConfigMap file at: $CONFIGMAP_FILE"
        exit 1
    fi
}

# Function to deploy the configmap
deploy_configmap() {
    log_step "Deploying ConfigMap '$CONFIGMAP_NAME' to namespace '$NAMESPACE'..."
    
    kubectl apply -f "$CONFIGMAP_FILE"
    
    if [ $? -eq 0 ]; then
        log_info "Successfully deployed ConfigMap '$CONFIGMAP_NAME'"
        return 0
    else
        log_error "Failed to deploy ConfigMap '$CONFIGMAP_NAME'"
        return 1
    fi
}

# Function to verify the configmap
verify_configmap() {
    log_step "Verifying ConfigMap deployment..."
    
    if kubectl get configmap "$CONFIGMAP_NAME" --namespace="$NAMESPACE" &> /dev/null; then
        log_info "✅ ConfigMap '$CONFIGMAP_NAME' exists in namespace '$NAMESPACE'"
        
        echo ""
        log_info "ConfigMap details:"
        kubectl describe configmap "$CONFIGMAP_NAME" --namespace="$NAMESPACE"
        
        echo ""
        log_info "ConfigMap data:"
        kubectl get configmap "$CONFIGMAP_NAME" --namespace="$NAMESPACE" -o yaml | grep -A 20 "^data:"
        
        return 0
    else
        log_error "❌ ConfigMap '$CONFIGMAP_NAME' not found in namespace '$NAMESPACE'"
        return 1
    fi
}

# Function to show usage
show_usage() {
    echo "ArgoCD ConfigMap Deployment Script for VorgabenUI"
    echo ""
    echo "Usage: $0 [OPTIONS]"
    echo ""
    echo "This script deploys Django configuration to the vorgabenui namespace for ArgoCD."
    echo ""
    echo "Options:"
    echo "  -h, --help                   Show this help message"
    echo "  --verify-only               Only verify existing ConfigMap, don't deploy"
    echo "  --dry-run                   Show what would be deployed without applying"
    echo ""
    echo "Configuration (hardcoded for ArgoCD):"
    echo "  Namespace: $NAMESPACE"
    echo "  ConfigMap Name: $CONFIGMAP_NAME"
    echo "  ConfigMap File: $CONFIGMAP_FILE"
    echo ""
    echo "Examples:"
    echo "  $0                          # Deploy ConfigMap"
    echo "  $0 --verify-only           # Verify existing ConfigMap"
    echo "  $0 --dry-run               # Preview deployment"
    echo ""
    echo "Note: Run this before deploying the ArgoCD deployment to ensure configuration is available."
}

# Parse command line arguments
VERIFY_ONLY=false
DRY_RUN=false

while [[ $# -gt 0 ]]; do
    case $1 in
        --verify-only)
            VERIFY_ONLY=true
            shift
            ;;
        --dry-run)
            DRY_RUN=true
            shift
            ;;
        -h|--help)
            show_usage
            exit 0
            ;;
        *)
            log_error "Unknown option: $1"
            show_usage
            exit 1
            ;;
    esac
done

# Main execution
main() {
    echo ""
    log_info "🚀 ArgoCD Django ConfigMap Deployment Script"
    log_info "============================================"
    echo ""
    log_info "Target Configuration:"
    log_info "  Namespace: $NAMESPACE"
    log_info "  ConfigMap Name: $CONFIGMAP_NAME"
    log_info "  ConfigMap File: $CONFIGMAP_FILE"
    echo ""
    
    # Perform checks
    log_step "Performing pre-flight checks..."
    check_kubectl
    check_configmap_file
    log_info "✅ All pre-flight checks passed"
    echo ""
    
    # Verify-only mode
    if [ "$VERIFY_ONLY" = true ]; then
        log_info "🔍 Verify-only mode - checking existing ConfigMap"
        verify_configmap
        exit $?
    fi
    
    # Dry-run mode
    if [ "$DRY_RUN" = true ]; then
        log_info "🔍 Dry-run mode - showing what would be deployed:"
        echo ""
        log_info "ConfigMap content that would be deployed:"
        cat "$CONFIGMAP_FILE"
        echo ""
        log_info "Would run: kubectl apply -f $CONFIGMAP_FILE"
        echo ""
        log_info "Run without --dry-run to execute the deployment"
        exit 0
    fi
    
    # Create namespace if it doesn't exist
    if ! kubectl get namespace "$NAMESPACE" &> /dev/null; then
        log_warn "Namespace '$NAMESPACE' does not exist, creating..."
        kubectl create namespace "$NAMESPACE"
        log_info "✅ Created namespace '$NAMESPACE'"
    fi
    
    # Deploy the ConfigMap
    if deploy_configmap; then
        echo ""
        # Verify deployment
        verify_configmap
        echo ""
        
        log_info "🎉 ConfigMap deployment completed successfully!"
        echo ""
        log_info "📋 Next steps:"
        log_info "1. Deploy the secret (if not already done):"
        echo "    ./scripts/deploy-argocd-secret.sh"
        echo ""
        log_info "2. Apply the updated deployment:"
        echo "    kubectl apply -f argocd/deployment.yaml"
        echo ""
        log_info "3. Verify Django pods start with proper configuration"
        echo ""
    else
        log_error "ConfigMap deployment failed"
        exit 1
    fi
}

# Run main function
main