Files
gott/Endpoints/BackupEndpoint.cs
T

66 lines
2.0 KiB
C#

using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
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<IResult> HandleBackup()
{
var dataDir = Path.Combine(AppContext.BaseDirectory, "data");
if (!Directory.Exists(dataDir))
return Results.NotFound(new { error = "Data-Ordner 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 entries = Directory.GetFileSystemEntries(dataDir)
.Select(e => Path.GetFileName(e))
.Where(e => e != "backup")
.ToArray();
var psi = new ProcessStartInfo
{
FileName = "tar",
RedirectStandardError = true,
UseShellExecute = false
};
psi.ArgumentList.Add("-czf");
psi.ArgumentList.Add(archivePath);
psi.ArgumentList.Add("-C");
psi.ArgumentList.Add(dataDir);
foreach (var entry in entries)
psi.ArgumentList.Add(entry);
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);
}
}