#!/bin/bash
# Cleanup script for Docker resources
# Use: ./shared/scripts/docker-cleanup.sh
# Use: ./shared/scripts/docker-cleanup.sh --full  (for aggressive cleanup)

set -e

echo "🧹 Aurora Docker Cleanup"
echo "========================"
echo ""

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

# Stop running containers for this project
echo "📦 Stopping Aurora containers..."
docker compose down 2>/dev/null || true

# Remove dangling images (untagged images from failed builds)
echo ""
echo "🗑️  Removing dangling images..."
docker image prune -f

# Check for --full flag for aggressive cleanup
if [[ "$1" == "--full" ]]; then
    echo ""
    echo "🔥 Full cleanup mode - removing all unused Docker resources..."
    
    # Remove all unused images, not just dangling ones
    echo "  → Removing unused images..."
    docker image prune -a -f
    
    # Remove build cache
    echo "  → Removing build cache..."
    docker builder prune -a -f
    
    # Remove unused volumes (except named ones we need)
    echo "  → Removing unused volumes..."
    docker volume prune -f
    
    # Remove unused networks
    echo "  → Removing unused networks..."
    docker network prune -f
    
    # Remove node_modules volumes
    echo "  → Removing node_modules volumes..."
    docker volume rm aurora_app_node_modules aurora_web_node_modules 2>/dev/null || true
    
    echo ""
    echo "✅ Full cleanup complete!"
else
    # Interactive mode
    echo ""
    read -p "🔧 Remove Docker build cache? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        docker builder prune -f
        echo "✓ Build cache cleared"
    fi

    echo ""
    read -p "🖼️  Remove ALL unused images (not just dangling)? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        docker image prune -a -f
        echo "✓ Unused images removed"
    fi

    echo ""
    read -p "📁 Remove node_modules volumes? (forces fresh install) (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        docker volume rm aurora_app_node_modules aurora_web_node_modules 2>/dev/null || true
        echo "✓ Node modules volumes removed"
    fi

    echo ""
    read -p "🧨 Run full system prune (removes ALL unused data)? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        docker system prune -a -f --volumes
        echo "✓ Full system prune complete"
    fi

    echo ""
    echo "✅ Cleanup complete!"
fi

echo ""
echo "📊 Docker disk usage after cleanup:"
docker system df
echo ""
echo "💡 Tip: Check container logs with: sudo du -sh /var/lib/docker/containers/*/*.log"
echo "💡 Tip: Truncate logs with: sudo truncate -s 0 /var/lib/docker/containers/*/*.log"
echo ""
echo "Run 'docker compose up --build' to rebuild"
