using System; using System.Diagnostics; using System.IO; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; namespace Gott.Endpoints; public static class BackupEndpoint { public static void MapBackupEndpoint(this IEndpointRouteBuilder app) { app.MapPost("/api/backup", HandleBackup); } private static async System.Threading.Tasks.Task HandleBackup() { var dataDir = Path.Combine(AppContext.BaseDirectory, "data"); var dbPath = Path.Combine(dataDir, "gott.db"); if (!File.Exists(dbPath)) return Results.NotFound(new { error = "Datenbank nicht gefunden" }); var backupDir = Path.Combine(dataDir, "backup"); Directory.CreateDirectory(backupDir); var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var archiveName = $"gott-{timestamp}.tar.gz"; var archivePath = Path.Combine(backupDir, archiveName); var psi = new ProcessStartInfo { FileName = "tar", ArgumentList = { "-czf", archivePath, "-C", dataDir, "gott.db" }, RedirectStandardError = true, UseShellExecute = false }; using (var process = Process.Start(psi)) { if (process == null) return Results.StatusCode(500); var stderr = await process.StandardError.ReadToEndAsync(); await process.WaitForExitAsync(); if (process.ExitCode != 0) return Results.Problem($"tar fehlgeschlagen: {stderr}"); } var bytes = await File.ReadAllBytesAsync(archivePath); return Results.File(bytes, "application/gzip", archiveName); } }