From 91176050c035d13597bf274ca0973e7296f31534 Mon Sep 17 00:00:00 2001
From: Renan Bernordi <altendorfme@gmail.com>
Date: Fri, 28 Feb 2025 11:29:46 -0300
Subject: [PATCH] adicionada ferramenta para limpar cache

---
 Dockerfile         |  5 ++-
 app/.env.sample    |  9 ++++-
 app/composer.json  |  3 +-
 app/config.php     |  1 +
 bin/cleanup        | 99 ++++++++++++++++++++++++++++++++++++++++++++++
 docker-compose.yml |  1 +
 6 files changed, 114 insertions(+), 4 deletions(-)
 create mode 100644 bin/cleanup

diff --git a/Dockerfile b/Dockerfile
index cac6a53..5df073c 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -10,6 +10,7 @@ RUN apt-get update && apt-get install -y \
     zip \
     git \
     htop \
+    cron \
     libzip-dev \
     libsqlite3-dev \
     && docker-php-ext-install zip opcache pdo_sqlite \
@@ -45,7 +46,9 @@ COPY default.conf /etc/nginx/sites-available/default
 
 # Copy and configure initialization script permissions
 COPY docker-entrypoint.sh /usr/local/bin/
-RUN chmod +x /usr/local/bin/docker-entrypoint.sh
+COPY bin/cleanup /usr/local/bin/
+RUN chmod +x /usr/local/bin/docker-entrypoint.sh \
+    && chmod +x /usr/local/bin/cleanup
 
 # Create cache, database, and logs folders
 RUN mkdir -p /app/cache /app/cache/database /app/logs
diff --git a/app/.env.sample b/app/.env.sample
index 4bd80ba..f4b523e 100644
--- a/app/.env.sample
+++ b/app/.env.sample
@@ -40,5 +40,10 @@ S3_ENDPOINT=
 # Selenium Configuration  
 SELENIUM_HOST=localhost:4444  
 
-# Debug Settings  
-DEBUG=false  
+# Debug Settings
+DEBUG=false
+
+# Cache Cleanup Settings
+# Number of days to keep cache files (*.gz)
+# If not set, no files will be cleaned
+CLEANUP_DAYS=7
diff --git a/app/composer.json b/app/composer.json
index d9b51dc..fa5e03f 100644
--- a/app/composer.json
+++ b/app/composer.json
@@ -5,7 +5,8 @@
         "php-curl-class/php-curl-class": "^11.0",
         "php-webdriver/webdriver": "^1.15",
         "monolog/monolog": "^3.8.1",
-        "nikic/fast-route": "^1.3"
+        "nikic/fast-route": "^1.3",
+        "league/climate": "^3.8"
     },
     "autoload": {
         "psr-4": {
diff --git a/app/config.php b/app/config.php
index d431cd4..51710f6 100644
--- a/app/config.php
+++ b/app/config.php
@@ -30,6 +30,7 @@ try {
     define('SITE_NAME', $_ENV['SITE_NAME']);
     define('SITE_DESCRIPTION', $_ENV['SITE_DESCRIPTION']);
     define('SITE_URL', $_ENV['SITE_URL']);
+    define('CLEANUP_DAYS', $_ENV['CLEANUP_DAYS'] ?? 0);
     
     // Optional settings with defaults
     define('DNS_SERVERS', $_ENV['DNS_SERVERS'] ?? '1.1.1.1, 8.8.8.8');
diff --git a/bin/cleanup b/bin/cleanup
new file mode 100644
index 0000000..3f8f9b0
--- /dev/null
+++ b/bin/cleanup
@@ -0,0 +1,99 @@
+#!/usr/bin/env php
+<?php
+
+/**
+ * Cache Cleanup Script
+ *
+ * Removes *.gz files from the cache directory that are older than the number
+ * of days specified in the define('CLEANUP_DAYS') environment variable.
+ * If define('CLEANUP_DAYS') is not set, no files will be cleaned.
+ */
+
+require_once __DIR__ . '/../app/vendor/autoload.php';
+
+use League\CLImate\CLImate;
+use Dotenv\Dotenv;
+
+$climate = new CLImate();
+$climate->bold()->out('Cache Cleanup Tool');
+$climate->br();
+
+$cleanupDays = 0;
+
+// Load environment variables from .env file
+try {
+    $dotenv = Dotenv::createImmutable(__DIR__ . '/../app');
+    $dotenv->load();
+    $climate->out('Environment variables loaded');
+    $cleanupDays = $_ENV['CLEANUP_DAYS'];
+} catch (\Exception $e) {
+    $climate->yellow()->out('Warning: ' . $e->getMessage());
+    // Continue execution even if .env file is not found
+}
+
+// Define cache directory constant if not already defined
+if (!defined('CACHE_DIR')) {
+    define('CACHE_DIR', __DIR__ . '/../app/cache');
+}
+
+// Check if define('CLEANUP_DAYS') is set
+if ($cleanupDays == 0) {
+    $climate->yellow()->out('CLEANUP_DAYS variable not set or 0. No files will be cleaned.');
+    exit(0);
+}
+
+// Validate define('CLEANUP_DAYS') is a positive integer
+$cleanupDays = (int)$cleanupDays;
+if ($cleanupDays <= 0) {
+    $climate->red()->out('CLEANUP_DAYS must be a positive integer. No files will be cleaned.');
+    exit(1);
+};
+
+// Calculate the cutoff timestamp
+$cutoffTime = time() - ($cleanupDays * 86400);
+
+// Get cache directory path
+$cacheDir = CACHE_DIR;
+
+$climate->out("Cleaning cache files older than {$cleanupDays} days from: {$cacheDir}");
+
+// Check if cache directory exists
+if (!is_dir($cacheDir)) {
+    $climate->red()->out("Cache directory not found: {$cacheDir}");
+    exit(1);
+}
+
+// Find all .gz files in the cache directory
+$gzFiles = glob($cacheDir . '/*.gz');
+$totalFiles = count($gzFiles);
+$deletedFiles = 0;
+
+if ($totalFiles === 0) {
+    $climate->out('No .gz files found in cache directory.');
+    exit(0);
+}
+
+$climate->out("Found {$totalFiles} .gz files in cache directory.");
+
+$progress = $climate->progress()->total($totalFiles);
+
+// Process each file
+foreach ($gzFiles as $index => $file) {
+    $progress->current($index + 1);
+    
+    // Get file modification time
+    $fileTime = filemtime($file);
+    
+    // Check if file is older than cutoff time
+    if ($fileTime < $cutoffTime) {
+        // Delete the file
+        if (unlink($file)) {
+            $deletedFiles++;
+        } else {
+            $climate->red()->out("Failed to delete: " . basename($file));
+        }
+    }
+}
+
+$climate->br();
+$climate->green()->out("Cleanup complete: {$deletedFiles} files deleted.");
\ No newline at end of file
diff --git a/docker-compose.yml b/docker-compose.yml
index 905d263..35ded47 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -16,6 +16,7 @@ services:
       - LANGUAGE=${LANGUAGE:-pt-br}
       - LOG_LEVEL=${LOG_LEVEL:-WARNING}
       - SELENIUM_HOST=${SELENIUM_HOST:-selenium-hub:4444}
+      - CLEANUP_DAYS=7 # Optional
     restart: unless-stopped
   # Selenium
   selenium-hub: