#!/bin/bash
set -e

# Configuration
REGISTRY_DATA="/mnt/HC_Volume_104575103/registry-data/docker/registry/v2"
KEEP_TAGS=3

echo "🏥 Starting Aggressive Registry & Docker Maintenance..."

# 1. Prune Registry Tags (Filesystem level)
for repo_dir in "$REGISTRY_DATA/repositories/mintel/"*; do
    repo_name=$(basename "$repo_dir")
    tags_dir="$repo_dir/_manifests/tags"
    
    if [ -d "$tags_dir" ]; then
        echo "🔍 Processing repository: mintel/$repo_name"
        
        # Prune various tag patterns
        PATTERNS=("main-*" "testing-*" "branch-*" "v*" "rc*" "[0-9a-f]*")
        
        for pattern in "${PATTERNS[@]}"; do
            echo "  📦 Pruning $pattern tags..."
            tags=$(ls -dt "$tags_dir"/${pattern} 2>/dev/null || true)
            count=0
            for tag_path in $tags; do
                tag_name=$(basename "$tag_path")
                if [[ "$tag_name" == "latest" ]]; then continue; fi
                
                ((++count))
                if [ $count -gt $KEEP_TAGS ]; then
                    echo "    🗑️ Deleting old tag: $tag_name"
                    rm -rf "$tag_path"
                fi
            done
        done

        # Always prune buildcache
        if [ -d "$tags_dir/buildcache" ]; then
            echo "  🧹 Deleting buildcache tag"
            rm -rf "$tags_dir/buildcache"
        fi
    fi
done

# 2. Run Garbage Collection
echo "♻️ Detecting Registry Container..."
REGISTRY_CONTAINER=$(docker ps --format "{{.Names}}" | grep registry | head -1 || true)

if [ -n "$REGISTRY_CONTAINER" ]; then
    echo "♻️ Running Registry Garbage Collection on $REGISTRY_CONTAINER..."
    docker exec "$REGISTRY_CONTAINER" bin/registry garbage-collect /etc/docker/registry/config.yml --delete-untagged
else
    echo "⚠️ Registry container not found. Skipping GC."
fi

# 3. Prune Host Docker resources (Shorter window: 24h)
echo "🧹 Pruning Host Docker resources..."
docker system prune -af --filter "until=24h"
docker volume prune -f

echo "✅ Maintenance complete!"
df -h /
