#!/bin/bash

# CodeTree Build Storage Cleanup Script
# This script helps minimize storage consumption by cleaning up build artifacts

set -e

echo "🧹 CodeTree Build Storage Cleanup"
echo "================================="

# Function to display size in human readable format
show_size() {
    if [ -d "$1" ]; then
        du -sh "$1" 2>/dev/null || echo "0B $1"
    else
        echo "0B $1 (not found)"
    fi
}

# Show current storage usage
echo "📊 Current storage usage:"
echo "Target directory: $(show_size target/)"
echo "Cargo cache: $(show_size ~/.cargo/registry/)"
echo "Cargo git cache: $(show_size ~/.cargo/git/)"
echo

# Clean target directory
if [ -d "target/" ]; then
    echo "🗑️  Cleaning target directory..."
    cargo clean
    echo "✅ Target directory cleaned"
else
    echo "ℹ️  No target directory found"
fi

# Clean cargo cache (optional - uncomment if needed)
# echo "🗑️  Cleaning cargo cache..."
# cargo cache --autoclean
# echo "✅ Cargo cache cleaned"

# Remove old build artifacts
echo "🗑️  Removing old build artifacts..."
find . -name "*.rlib" -delete 2>/dev/null || true
find . -name "*.rmeta" -delete 2>/dev/null || true
find . -name "*.d" -delete 2>/dev/null || true
find . -name "*.o" -delete 2>/dev/null || true
echo "✅ Old build artifacts removed"

# Clean up temporary files
echo "🗑️  Cleaning temporary files..."
find . -name "*~" -delete 2>/dev/null || true
find . -name "*.swp" -delete 2>/dev/null || true
find . -name "*.swo" -delete 2>/dev/null || true
find . -name ".DS_Store" -delete 2>/dev/null || true
echo "✅ Temporary files cleaned"

# Show final storage usage
echo
echo "📊 Storage usage after cleanup:"
echo "Target directory: $(show_size target/)"
echo
echo "🎉 Cleanup completed!"
echo
echo "💡 Tips to minimize storage consumption:"
echo "   • Run 'cargo clean' regularly"
echo "   • Use 'cargo build --release' only when needed"
echo "   • Consider using a shared target directory with CARGO_TARGET_DIR"
echo "   • Run this script periodically: ./scripts/cleanup.sh"