<?php
/**
 * Cache Cleanup Script
 * Removes old cached executables and temporary directories
 * Run this periodically via cron or manually
 */

$base_dir = dirname(__DIR__);
$cache_dir = $base_dir . DIRECTORY_SEPARATOR . 'cache';

$cleaned_files = 0;
$cleaned_dirs = 0;
$freed_bytes = 0;

// Clean old compiled executables (older than 7 days)
$compiled_dir = $cache_dir . DIRECTORY_SEPARATOR . 'compiled';
if (is_dir($compiled_dir)) {
    $files = glob($compiled_dir . DIRECTORY_SEPARATOR . '*.exe');
    foreach ($files as $file) {
        if (file_exists($file) && (time() - filemtime($file)) > 604800) {
            $size = filesize($file);
            if (unlink($file)) {
                $cleaned_files++;
                $freed_bytes += $size;
            }
        }
    }
}

// Clean orphaned execution directories
$exec_dirs = glob($cache_dir . DIRECTORY_SEPARATOR . 'exec_*');
foreach ($exec_dirs as $dir) {
    if (is_dir($dir)) {
        // Remove directory if older than 1 hour (safety cleanup)
        if ((time() - filemtime($dir)) > 3600) {
            // Remove all files in directory
            $files = glob($dir . DIRECTORY_SEPARATOR . '*');
            foreach ($files as $file) {
                if (is_file($file)) {
                    $size = filesize($file);
                    unlink($file);
                    $freed_bytes += $size;
                }
            }
            // Remove directory
            if (rmdir($dir)) {
                $cleaned_dirs++;
            }
        }
    }
}

// Format output
$freed_mb = round($freed_bytes / 1024 / 1024, 2);

echo "Cache Cleanup Complete\n";
echo "=====================\n";
echo "Files removed: $cleaned_files\n";
echo "Directories removed: $cleaned_dirs\n";
echo "Space freed: {$freed_mb} MB\n";

// Log the cleanup
$log_file = $cache_dir . DIRECTORY_SEPARATOR . 'cleanup.log';
$log_entry = date('Y-m-d H:i:s') . " - Cleaned $cleaned_files files, $cleaned_dirs dirs, freed {$freed_mb} MB\n";
file_put_contents($log_file, $log_entry, FILE_APPEND);
?>
