mailwolt/database/seeders/SystemBackupSeeder.php

81 lines
3.0 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Str;
use App\Models\BackupPolicy;
class SystemBackupSeeder extends Seeder
{
/**
* Mappe einfache Intervalle auf Cron (Fallback, falls kein explizites Cron gesetzt ist)
*/
protected function intervalToCron(string $interval): string
{
return match (Str::lower($interval)) {
'daily' => '0 3 * * *', // täglich 03:00
'weekly' => '0 3 * * 0', // sonntags 03:00
'monthly' => '0 3 1 * *', // am 1. 03:00
default => '0 3 * * *',
};
}
public function run(): void
{
// --- Basiskonfiguration aus .env (kannst du im Installer befüllen)
$enabled = (bool) env('BACKUP_ENABLED', false);
$interval = (string) env('BACKUP_INTERVAL', 'daily');
$cron = (string) (env('BACKUP_DEFAULT_CRON') ?: $this->intervalToCron($interval));
$targetType = (string) env('BACKUP_TARGET_TYPE', 'local'); // local|s3
$targetPath = (string) env('BACKUP_DIR', '/var/backups/mailwolt');
$retentionCount = (int) env('BACKUP_RETENTION_COUNT', 7);
// --- optionale S3/MinIO-Angaben
$s3Bucket = env('BACKUP_S3_BUCKET');
$s3Region = env('BACKUP_S3_REGION');
$s3Endpoint = env('BACKUP_S3_ENDPOINT');
$s3Key = env('BACKUP_S3_KEY');
$s3Secret = env('BACKUP_S3_SECRET');
// Bestehende „Standard“-Policy aktualisieren oder anlegen
$policy = BackupPolicy::query()->firstOrCreate(
['name' => 'Standard'],
['enabled' => false] // wird unten überschrieben; sorgt nur für Existenz
);
$payload = [
'enabled' => $enabled,
'schedule_cron' => $cron,
'target_type' => $targetType, // 'local' oder 's3'
'target_path' => $targetPath, // bei local: Verzeichnis
'retention_count' => $retentionCount,
];
// S3-Felder nur setzen, wenn Ziel = s3
if (Str::lower($targetType) === 's3') {
$payload = array_merge($payload, [
's3_bucket' => $s3Bucket,
's3_region' => $s3Region,
's3_endpoint' => $s3Endpoint,
// Schlüssel nur speichern, wenn vorhanden verschlüsselt
's3_key_enc' => $s3Key ? Crypt::encryptString($s3Key) : $policy->s3_key_enc,
's3_secret_enc' => $s3Secret ? Crypt::encryptString($s3Secret) : $policy->s3_secret_enc,
]);
} else {
// lokales Ziel: S3-Felder leeren
$payload = array_merge($payload, [
's3_bucket' => null,
's3_region' => null,
's3_endpoint' => null,
's3_key_enc' => null,
's3_secret_enc' => null,
]);
}
$policy->fill($payload)->save();
}
}