#!/bin/bash

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}🧹 Pipeline Cleanup Utility${NC}"
echo "==========================="

echo -e "${YELLOW}⚠️  This will remove:${NC}"
echo "  - All stopped containers"
echo "  - All unused networks"
echo "  - All unused images"
echo "  - All build cache"
echo ""
echo -e "${RED}⚠️  This will NOT remove:${NC}"
echo "  - Running containers"
echo "  - Data volumes (unless specified)"
echo ""

read -p "Continue with cleanup? (y/N): " -n 1 -r
echo

if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${BLUE}🧹 Starting cleanup...${NC}"
    
    # Stop services first
    echo -e "${BLUE}⏹️  Stopping services...${NC}"
    docker-compose down
    
    # Clean up Docker system
    echo -e "${BLUE}🗑️  Removing unused containers, networks, and images...${NC}"
    docker system prune -f
    
    # Optional: Remove volumes
    read -p "Remove data volumes? This will delete all database data! (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo -e "${YELLOW}🗑️  Removing volumes...${NC}"
        docker-compose down -v
        docker volume prune -f
    fi
    
    # Optional: Remove all images
    read -p "Remove all Docker images? This will require re-downloading. (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo -e "${YELLOW}🗑️  Removing all images...${NC}"
        docker image prune -a -f
    fi
    
    echo ""
    echo -e "${GREEN}✅ Cleanup completed!${NC}"
    echo -e "${BLUE}📊 Current system usage:${NC}"
    docker system df
else
    echo -e "${BLUE}❌ Cleanup cancelled${NC}"
fi
