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

162 lines
5.3 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Models\Backup;
use Illuminate\Console\Command;
class BackupRestoreCommand extends Command
{
protected $signature = 'backup:restore {backupId}';
protected $description = 'Restore a database backup (CLI only)';
public function handle(): int
{
$backupId = $this->argument('backupId');
$backup = Backup::find($backupId);
if (! $backup || $backup->status !== 'completed') {
$this->error("Backup #{$backupId} not found or not completed.");
return self::FAILURE;
}
$config = config('backup');
$db = $config['database'];
$password = $config['password'];
$zipPath = storage_path("app/private/backups/{$backup->filename}");
if (! file_exists($zipPath)) {
$this->error("Backup file not found: {$zipPath}");
return self::FAILURE;
}
if (empty($password)) {
$this->error('BACKUP_PASSWORD no está configurada en el .env. Agregá BACKUP_PASSWORD=<clave> y volvé a intentar.');
return self::FAILURE;
}
$tempDir = storage_path('app/private/temp_restore_'.now()->format('Y-m-d_His'));
mkdir($tempDir, 0755, true);
try {
$this->info('Creating safety backup of current database...');
$safetyFile = $tempDir.'/pre_restore.sql';
$dumpCommand = sprintf(
'%s --host=%s --port=%s --user=%s --password=%s --single-transaction --result-file=%s %s 2>&1',
escapeshellarg($config['mysqldump_path']),
escapeshellarg($db['host']),
escapeshellarg((string) $db['port']),
escapeshellarg($db['username']),
escapeshellarg($db['password']),
escapeshellarg($safetyFile),
escapeshellarg($db['database'])
);
exec($dumpCommand, $output, $exitCode);
if ($exitCode !== 0) {
$this->warn('Warning: Could not create safety backup. Continuing anyway.');
}
$this->info('Decrypting backup...');
$extractCommand = sprintf(
'%s x -p%s -o%s -y %s 2>&1',
escapeshellarg($config['seven_zip_path']),
escapeshellarg($password),
escapeshellarg($tempDir),
escapeshellarg($zipPath)
);
exec($extractCommand, $output, $exitCode);
if ($exitCode !== 0) {
throw new \RuntimeException('7-Zip extraction failed: '.implode("\n", $output));
}
$sqlFiles = glob($tempDir.'/*.sql');
if (empty($sqlFiles)) {
throw new \RuntimeException('No SQL file found in extracted backup.');
}
$sqlFile = $sqlFiles[0];
$this->info('Dropping all tables...');
$config2 = config('backup');
$db2 = $config2['database'];
\DB::unprepared('SET FOREIGN_KEY_CHECKS = 0');
$tables = \DB::select('SHOW TABLES');
$dbName = \DB::getDatabaseName();
$tableKey = "Tables_in_{$dbName}";
foreach ($tables as $table) {
$tableName = $table->$tableKey;
\DB::statement("DROP TABLE IF EXISTS `{$tableName}`");
}
\DB::unprepared('SET FOREIGN_KEY_CHECKS = 1');
$this->info('Restoring database...');
$passwordArg = $db['password'] !== '' ? '--password='.escapeshellarg($db['password']) : '--password=""';
$restoreCommand = sprintf(
'%s --host=%s --port=%s --user=%s %s %s',
escapeshellarg($config['mysql_path']),
escapeshellarg($db['host']),
escapeshellarg((string) $db['port']),
escapeshellarg($db['username']),
$passwordArg,
escapeshellarg($db['database'])
);
$descriptors = [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
];
$process = proc_open($restoreCommand, $descriptors, $pipes);
if (! is_resource($process)) {
throw new \RuntimeException('No se pudo iniciar mysql.exe para la restauración.');
}
fwrite($pipes[0], file_get_contents($sqlFile));
fclose($pipes[0]);
$stdout = stream_get_contents($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$exitCode = proc_close($process);
if ($exitCode !== 0) {
throw new \RuntimeException('MySQL restore failed: '.($stderr ?: $stdout));
}
$this->info("Database restored successfully from: {$backup->filename}");
$this->cleanupTempDir($tempDir);
return self::SUCCESS;
} catch (\Throwable $e) {
$this->error("Restore failed: {$e->getMessage()}");
$this->cleanupTempDir($tempDir);
return self::FAILURE;
}
}
private function cleanupTempDir(string $dir): void
{
$files = glob($dir.'/*');
foreach ($files as $file) {
if (is_file($file)) {
@unlink($file);
}
}
@rmdir($dir);
}
}