55 lines
1.7 KiB
C#
55 lines
1.7 KiB
C#
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<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 psi = new ProcessStartInfo
|
|
{
|
|
FileName = "tar",
|
|
ArgumentList = { "-czf", archivePath, "--exclude=backup", "-C", dataDir, "." },
|
|
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);
|
|
}
|
|
}
|