Files
mgap/app/Console/Commands/BackupCreateCommand.php
T
2026-09-18 23:35:22 -03:00

196 lines
6.3 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Models\Backup;
use App\Support\BackupRetention;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class BackupCreateCommand extends Command
{
protected $signature = 'backup:create {--frequency=}';
protected $description = 'Create a database backup with mysqldump and 7zip encryption';
public function handle(): int
{
$frequency = $this->option('frequency');
if ($frequency === null) {
$settings = DB::table('backup_settings')->first();
if (! $settings || ! $settings->is_active) {
$this->info('Backup scheduler is not active. Skipping.');
return self::SUCCESS;
}
$frequency = $settings->frequency;
if ($frequency === 'manual') {
$this->info('Backup frequency is manual; skipping scheduler.');
return self::SUCCESS;
}
if (! $this->shouldRun($frequency, $settings)) {
$this->info("Backup not scheduled for now (frequency: {$frequency}).");
return self::SUCCESS;
}
}
$config = config('backup');
$db = $config['database'];
$password = $config['password'];
$timestamp = now()->format('Y-m-d_His');
$sqlFile = storage_path("app/private/temp_dump_{$timestamp}.sql");
$zipFile = storage_path("app/private/backups/backup_{$timestamp}.zip");
if (empty($password)) {
$message = 'BACKUP_PASSWORD no está configurada en el .env. Agregá BACKUP_PASSWORD=<clave> y volvé a intentar.';
Backup::create([
'filename' => "backup_{$timestamp}.zip",
'status' => 'failed',
'frequency' => $frequency,
'created_by' => auth()->id() ?? 1,
'started_at' => now(),
'completed_at' => now(),
'error_message' => $message,
]);
$this->error($message);
return self::FAILURE;
}
$backupDir = storage_path('app/private/backups');
if (! is_dir($backupDir)) {
mkdir($backupDir, 0755, true);
}
$backup = Backup::create([
'filename' => "backup_{$timestamp}.zip",
'status' => 'pending',
'frequency' => $frequency,
'created_by' => auth()->id() ?? 1,
'started_at' => now(),
]);
$this->info("Starting backup: backup_{$timestamp}.zip");
try {
$this->info('Running mysqldump...');
$dumpCommand = sprintf(
'%s --host=%s --port=%s --user=%s --password=%s --single-transaction --routines --triggers --result-file=%s %s 2>&1',
escapeshellarg($config['mysqldump_path']),
escapeshellarg($db['host']),
escapeshellarg((string) $db['port']),
escapeshellarg($db['username']),
escapeshellarg($db['password']),
escapeshellarg($sqlFile),
escapeshellarg($db['database'])
);
$output = [];
$exitCode = 0;
exec($dumpCommand, $output, $exitCode);
if ($exitCode !== 0) {
throw new \RuntimeException('mysqldump failed: '.implode("\n", $output));
}
if (! file_exists($sqlFile) || filesize($sqlFile) === 0) {
throw new \RuntimeException('SQL dump file is empty or was not created.');
}
$originalSize = filesize($sqlFile);
$this->info('Dump created: '.number_format($originalSize).' bytes');
$this->info('Compressing and encrypting with 7-Zip...');
$zipCommand = sprintf(
'%s a -tzip -mem=AES256 -p%s -y %s %s 2>&1',
escapeshellarg($config['seven_zip_path']),
escapeshellarg($password),
escapeshellarg($zipFile),
escapeshellarg($sqlFile)
);
exec($zipCommand, $output, $exitCode);
if ($exitCode !== 0) {
throw new \RuntimeException('7-Zip failed: '.implode("\n", $output));
}
if (! file_exists($zipFile)) {
throw new \RuntimeException('ZIP file was not created.');
}
$compressedSize = filesize($zipFile);
$backup->update([
'status' => 'completed',
'original_size' => $originalSize,
'compressed_size' => $compressedSize,
'completed_at' => now(),
]);
$this->info("Backup completed: {$backup->filename} ({$compressedSize} bytes)");
$pruned = BackupRetention::prune($config['retention']);
if ($pruned > 0) {
$this->info("Pruned {$pruned} old backup(s).");
}
if ($frequency !== 'manual') {
DB::table('backup_settings')->update(['last_run_at' => now()]);
}
@unlink($sqlFile);
return self::SUCCESS;
} catch (\Throwable $e) {
$backup->update([
'status' => 'failed',
'error_message' => $e->getMessage(),
'completed_at' => now(),
]);
$this->error("Backup failed: {$e->getMessage()}");
@unlink($sqlFile);
@unlink($zipFile);
return self::FAILURE;
}
}
private function shouldRun(string $frequency, object $settings): bool
{
$now = now();
$runTime = $settings->run_time ? substr($settings->run_time, 0, 5) : '02:00';
if ($now->format('H:i') !== $runTime) {
return false;
}
if (isset($settings->last_run_at) && $settings->last_run_at) {
$lastRun = \Carbon\Carbon::parse($settings->last_run_at);
if ($lastRun->toDateString() === $now->toDateString()) {
return false;
}
}
$runDay = isset($settings->run_day) ? (int) $settings->run_day : null;
return match ($frequency) {
'daily' => true,
'weekly' => $runDay !== null ? $now->dayOfWeek === $runDay : $now->isSunday(),
'monthly' => $runDay !== null ? $now->day === $runDay : $now->day === 1,
default => false,
};
}
}