#!/bin/bash
# Docker Cleanup Script for Local Kubernetes Development
# This script helps prevent disk space issues by cleaning up unused Docker resources

set -e

echo "🧹 Docker Cleanup Script for Bakery-IA Local Development"
echo "========================================================="
echo ""

# Check if we should run automatically or ask for confirmation
AUTO_MODE=${1:-""}

# Show current disk usage
echo "📊 Current Docker Disk Usage:"
docker system df
echo ""

# Check Kind node disk usage if cluster is running
if docker ps | grep -q "bakery-ia-local-control-plane"; then
    echo "📊 Kind Node Disk Usage:"
    docker exec bakery-ia-local-control-plane df -h / /var | grep -E "(Filesystem|overlay|/dev/vdb1)"
    echo ""
fi

# Calculate reclaimable space
RECLAIMABLE=$(docker system df | grep "Images" | awk '{print $4}')
echo "💾 Estimated reclaimable space: $RECLAIMABLE"
echo ""

# Ask for confirmation unless in auto mode
if [ "$AUTO_MODE" != "--auto" ]; then
    read -p "Do you want to proceed with cleanup? (y/n) " -n 1 -r
    echo ""
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "❌ Cleanup cancelled"
        exit 0
    fi
fi

echo "🚀 Starting cleanup..."
echo ""

# Remove unused images (keep images from last 24 hours)
echo "1️⃣ Removing unused Docker images..."
docker image prune -af --filter "until=24h" || true
echo ""

# Remove unused volumes
echo "2️⃣ Removing unused Docker volumes..."
docker volume prune -f || true
echo ""

# Remove build cache
echo "3️⃣ Removing build cache..."
docker builder prune -af || true
echo ""

# Show results
echo "✅ Cleanup completed!"
echo ""
echo "📊 Final Docker Disk Usage:"
docker system df
echo ""

# Check Kind node disk usage if cluster is running
if docker ps | grep -q "bakery-ia-local-control-plane"; then
    echo "📊 Kind Node Disk Usage After Cleanup:"
    docker exec bakery-ia-local-control-plane df -h / /var | grep -E "(Filesystem|overlay|/dev/vdb1)"
    echo ""

    # Warn if still above 80%
    USAGE=$(docker exec bakery-ia-local-control-plane df -h /var | tail -1 | awk '{print $5}' | sed 's/%//')
    if [ "$USAGE" -gt 80 ]; then
        echo "⚠️  Warning: Disk usage is still above 80%. Consider:"
        echo "   - Deleting and recreating the Kind cluster"
        echo "   - Increasing Docker's disk allocation"
        echo "   - Running: docker system prune -a --volumes -f"
    fi
fi

echo "🎉 All done!"
