#!/usr/bin/env bash

set -e

# Verify all containers have resource limits
# This script checks all Kubernetes manifests for resource limits

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"


log_success "Verifying resource limits in all Kubernetes manifests..."

ERRORS=0
WARNINGS=0

# Find all YAML files
YAML_FILES=$(find "$PROJECT_ROOT/k8s" "$PROJECT_ROOT/helm" "$PROJECT_ROOT/monitoring/k8s" -name "*.yaml" -o -name "*.yml" 2>/dev/null)

for file in $YAML_FILES; do
    # Skip if file doesn't exist or is not a regular file
    [ ! -f "$file" ] && continue
    
    # Check if file contains containers
    if grep -q "containers:" "$file" || grep -q "initContainers:" "$file"; then
        # Extract container names
        CONTAINERS=$(grep -A 5 "containers:" "$file" | grep "name:" | awk '{print $2}' | tr -d '"' || true)
        INIT_CONTAINERS=$(grep -A 5 "initContainers:" "$file" | grep "name:" | awk '{print $2}' | tr -d '"' || true)
        
        ALL_CONTAINERS="$CONTAINERS $INIT_CONTAINERS"
        
        for container in $ALL_CONTAINERS; do
            if [ -z "$container" ]; then
                continue
            fi
            
            # Check if container has resources section
            if ! grep -A 20 "name:.*$container" "$file" | grep -q "resources:"; then
                log_error "✗ $file: Container '$container' missing resources"
                ERRORS=$((ERRORS + 1))
            else
                # Check for limits
                if ! grep -A 20 "name:.*$container" "$file" | grep -A 10 "resources:" | grep -q "limits:"; then
                    log_warn "⚠ $file: Container '$container' missing limits"
                    WARNINGS=$((WARNINGS + 1))
                else
                    # Check for requests
                    if ! grep -A 20 "name:.*$container" "$file" | grep -A 10 "resources:" | grep -q "requests:"; then
                        log_warn "⚠ $file: Container '$container' missing requests"
                        WARNINGS=$((WARNINGS + 1))
                    else
                        log_success "✓ $file: Container '$container' has resources"
                    fi
                fi
            fi
        done
    fi
done

log_success "Verification complete"
echo -e "Errors: $ERRORS"
echo -e "Warnings: $WARNINGS"

if [ $ERRORS -gt 0 ]; then
    log_error "Some containers are missing resource limits!"
    exit 1
fi

if [ $WARNINGS -gt 0 ]; then
    log_warn "Some containers are missing resource requests"
    exit 0
fi

log_success "All containers have proper resource limits and requests!"
exit 0

