#!/bin/bash

# Docker Cleanup Script
# This script removes all Docker resources to free up disk space

set -e

echo "🧹 Docker Cleanup Script"
echo "========================"
echo ""

# Function to display size before cleanup
show_current_usage() {
    echo "📊 Current Docker Disk Usage:"
    docker system df
    echo ""
}

# Function to confirm action
confirm() {
    read -p "⚠️  This will remove ALL Docker resources. Continue? (y/N) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "❌ Cleanup cancelled."
        exit 1
    fi
}

# Show current usage
show_current_usage

# Confirm with user
confirm

echo ""
echo "🛑 Stopping all running containers..."
docker stop $(docker ps -aq) 2>/dev/null || echo "No running containers to stop"

echo ""
echo "🗑️  Removing all containers..."
docker rm $(docker ps -aq) 2>/dev/null || echo "No containers to remove"

echo ""
echo "🗑️  Removing all images..."
docker rmi $(docker images -q) -f 2>/dev/null || echo "No images to remove"

echo ""
echo "🗑️  Removing all volumes..."
docker volume rm $(docker volume ls -q) 2>/dev/null || echo "No volumes to remove"

echo ""
echo "🗑️  Removing all networks (except defaults)..."
docker network rm $(docker network ls -q) 2>/dev/null || echo "No custom networks to remove"

echo ""
echo "🗑️  Removing all build cache..."
docker builder prune -af 2>/dev/null || echo "No build cache to remove"

echo ""
echo "🗑️  Final system prune..."
docker system prune -af --volumes

echo ""
echo "✅ Cleanup complete!"
echo ""
echo "📊 Final Docker Disk Usage:"
docker system df

echo ""
echo "💡 Tip: Run 'bash dc.sh' to rebuild and start your containers"
