#\!/bin/bash

set -e
set -o pipefail

# Usage function
usage() {
    echo "Usage: wild-cluster-services-generate [options]"
    echo ""
    echo "Generate cluster services setup files by compiling templates."
    echo ""
    echo "Options:"
    echo "  -h, --help          Show this help message"
    echo "  --force             Force regeneration even if files exist"
    echo ""
    echo "This script will:"
    echo "  - Copy cluster service templates from WC_ROOT to WC_HOME"
    echo "  - Compile all templates with current configuration"
    echo "  - Prepare services for installation"
    echo ""
    echo "Requirements:"
    echo "  - Must be run from a wild-cloud directory"
    echo "  - Basic cluster configuration must be completed"
    echo "  - Service configuration (DNS, storage, etc.) must be completed"
}

# Parse arguments
FORCE=false
while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            usage
            exit 0
            ;;
        --force)
            FORCE=true
            shift
            ;;
        -*)
            echo "Unknown option $1"
            usage
            exit 1
            ;;
        *)
            echo "Unexpected argument: $1"
            usage
            exit 1
            ;;
    esac
done

# Initialize Wild Cloud environment
if [ -z "${WC_ROOT}" ]; then
    print "WC_ROOT is not set."
    exit 1
else
    source "${WC_ROOT}/scripts/common.sh"
    init_wild_env
fi

# =============================================================================
# CLUSTER SERVICES SETUP GENERATION
# =============================================================================

print_header "Cluster Services Setup Generation"

SOURCE_DIR="${WC_ROOT}/setup/cluster-services"
DEST_DIR="${WC_HOME}/setup/cluster-services"

# Check if source directory exists
if [ ! -d "$SOURCE_DIR" ]; then
    print_error "Cluster setup source directory not found: $SOURCE_DIR"
    print_info "Make sure the wild-cloud repository is properly set up"
    exit 1
fi

# Check if destination already exists
if [ -d "$DEST_DIR" ] && [ "$FORCE" = false ]; then
    print_warning "Cluster setup directory already exists: $DEST_DIR"
    read -p "Overwrite existing files? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        print_info "Skipping cluster services generation"
        exit 0
    fi
    print_info "Regenerating cluster setup files..."
    rm -rf "$DEST_DIR"
elif [ "$FORCE" = true ] && [ -d "$DEST_DIR" ]; then
    print_info "Force regeneration enabled, removing existing files..."
    rm -rf "$DEST_DIR"
fi

# Copy and compile cluster setup files
print_info "Copying and compiling cluster setup files from repository..."
mkdir -p "${WC_HOME}/setup"

# Copy README if it doesn't exist
if [ ! -f "${WC_HOME}/setup/README.md" ]; then
    cp "${WC_ROOT}/setup/README.md" "${WC_HOME}/setup/README.md"
fi

# Create destination directory
mkdir -p "$DEST_DIR"

# First, copy root-level files from setup/cluster/ (install-all.sh, get_helm.sh, etc.)
print_info "Copying root-level cluster setup files..."
for item in "$SOURCE_DIR"/*; do
    if [ -f "$item" ]; then
        item_name=$(basename "$item")
        print_info "  Copying: ${item_name}"
        cp "$item" "$DEST_DIR/$item_name"
    fi
done

# Then, process each service directory in the source
print_info "Processing service directories..."
for service_dir in "$SOURCE_DIR"/*; do
    if [ ! -d "$service_dir" ]; then
        continue
    fi
    
    service_name=$(basename "$service_dir")
    dest_service_dir="$DEST_DIR/$service_name"
    
    print_info "Processing service: $service_name"
    
    # Create destination service directory
    mkdir -p "$dest_service_dir"
    
    # Copy all files except kustomize.template directory
    for item in "$service_dir"/*; do
        item_name=$(basename "$item")
        
        if [ "$item_name" = "kustomize.template" ]; then
            # Compile kustomize.template to kustomize directory
            if [ -d "$item" ]; then
                print_info "  Compiling kustomize templates for $service_name"
                wild-compile-template-dir --clean "$item" "$dest_service_dir/kustomize"
            fi
        else
            # Copy other files as-is (install.sh, README.md, etc.)
            if [ -f "$item" ]; then
                # Compile individual template files
                if grep -q "{{" "$item" 2>/dev/null; then
                    print_info "  Compiling: ${item_name}"
                    wild-compile-template < "$item" > "$dest_service_dir/$item_name"
                else
                    cp "$item" "$dest_service_dir/$item_name"
                fi
            elif [ -d "$item" ]; then
                cp -r "$item" "$dest_service_dir/"
            fi
        fi
    done
done

print_success "Cluster setup files copied and compiled"

# Verify required configuration
print_info "Verifying service configuration..."

MISSING_CONFIG=()

# Check essential configuration values
if [ -z "$(wild-config cluster.name 2>/dev/null)" ]; then
    MISSING_CONFIG+=("cluster.name")
fi

if [ -z "$(wild-config cloud.domain 2>/dev/null)" ]; then
    MISSING_CONFIG+=("cloud.domain")
fi

if [ -z "$(wild-config cluster.ipAddressPool 2>/dev/null)" ]; then
    MISSING_CONFIG+=("cluster.ipAddressPool")
fi

if [ -z "$(wild-config operator.email 2>/dev/null)" ]; then
    MISSING_CONFIG+=("operator.email")
fi

if [ ${#MISSING_CONFIG[@]} -gt 0 ]; then
    print_warning "Some required configuration values are missing:"
    for config in "${MISSING_CONFIG[@]}"; do
        print_warning "  - $config"
    done
    print_info "Run 'wild-setup' to complete the configuration"
fi

print_success "Cluster services setup generation completed!"
echo ""
print_info "Generated setup directory: $DEST_DIR"
echo ""
print_info "Available services:"
for service_dir in "$DEST_DIR"/*; do
    if [ -d "$service_dir" ] && [ -f "$service_dir/install.sh" ]; then
        service_name=$(basename "$service_dir")
        print_info "  - $service_name"
    fi
done

echo ""
print_info "Next steps:"
echo "  1. Review the generated configuration files in $DEST_DIR"
echo "  2. Make sure your cluster is running and kubectl is configured"
echo "  3. Install services with: wild-cluster-services-up"
echo "  4. Or install individual services by running their install.sh scripts"

print_success "Ready for cluster services installation!"