#!/bin/bash

set -euo pipefail

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"

echo "🧹 Clearing build caches for simple-object-server"

# Function to show what we're doing
function title() {
    echo "----------------------------------------"
    local text="$1"
    local line_length=40
    local text_length=${#text}
    local padding=$(( (line_length - text_length) / 2 ))
    printf "%*s%s%*s\n" $padding "" "$text" $padding ""
    echo "----------------------------------------"
}

# Remove local output directory
if [ -d "${SCRIPT_DIR}/output" ]; then
    title "Removing local output directory"
    rm -rf "${SCRIPT_DIR}/output"
    echo "✅ Removed ${SCRIPT_DIR}/output"
else
    echo "ℹ️  No local output directory to remove"
fi

# Clear Docker build cache for our project
title "Clearing Docker BuildKit cache"

# Remove any existing builder and recreate it (this clears cache)
PROJECT="simple-object-server"
docker buildx rm ${PROJECT}-multiarch 2>/dev/null || true
echo "✅ Removed Docker buildx builder"

# Prune Docker build cache
docker buildx prune -f
echo "✅ Pruned Docker BuildKit cache"

# Clear Docker system cache (more aggressive)
title "Clearing Docker system cache"
docker system prune -f
echo "✅ Pruned Docker system cache"

# Optional: Clear all Docker build cache (very aggressive)
read -p "🚨 Clear ALL Docker build cache? This affects all projects (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    docker builder prune -af
    echo "✅ Cleared ALL Docker build cache"
else
    echo "ℹ️  Skipped clearing all Docker build cache"
fi

title "Cache clearing complete"
echo "🎉 All caches have been cleared!"
echo ""
echo "Next build will be from scratch but subsequent builds will be fast again."