using System.Collections; using Anubis.Core; using Anubis.Db; using Anubis.Platform; namespace Anubis.Server; /// /// Command line export and import (SPEC 5.4), the way to change engine: with the server stopped, export from the old /// database, point the configuration to the new one, import. The import goes only into an empty database and renews /// the installation fingerprint, so the old copy is no longer accepted (SPEC 15.1). /// internal static class DatabaseCommand { public static async Task RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary? environment = null) { output ??= Console.Out; if (args.Length < 2 || args[0] is not ("export" or "import")) { await output.WriteLineAsync("Uso: anubis db export | anubis db import [--data-dir , obbligatoria fuori dal container]").ConfigureAwait(false); return 2; } environment ??= Environment.GetEnvironmentVariables().Cast().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal); var options = ServerOptions.Parse(args[2..], environment); var config = options.LoadConfig(environment); if (!config.IsComplete) { await output.WriteLineAsync("La configurazione d'avvio non รจ completa:").ConfigureAwait(false); foreach (var problem in config.Problems) { await output.WriteLineAsync($"- {problem.Setting}: {problem.What} {problem.Remedy}").ConfigureAwait(false); } return 1; } Redactor.Register(config.Db!.Password); var clock = new SystemClock(); var folder = Path.GetFullPath(args[1]); try { if (args[0] == "import") { // Read before the database is opened: a wrong folder must not leave a new empty SQLite file behind. await Archive.ReadIndexAsync(folder).ConfigureAwait(false); config.Data.Ensure(); } // Moving to SQLite, the file does not exist yet: the user asked for it by name, unlike a start (trap 20). await using var db = Database.Open(config.Db!, allowCreate: args[0] == "import"); if (args[0] == "export") { var index = await Archive.ExportAsync(db, folder, clock).ConfigureAwait(false); await output.WriteLineAsync($"Esportate {index.Tables.Sum(t => t.Count)} righe di {index.Tables.Count} tabelle in {folder}.").ConfigureAwait(false); return 0; } var imported = await Archive.ImportAsync(db, folder, clock).ConfigureAwait(false); await Installation.RenewAsync(db, config.Data, clock, "Archivio importato").ConfigureAwait(false); await output.WriteLineAsync($"Importate {imported.Tables.Sum(t => t.Count)} righe di {imported.Tables.Count} tabelle: conteggi e totali coincidono. " + "Al prossimo avvio il bot riparte protetto.").ConfigureAwait(false); return 0; } catch (Exception ex) when (Forms.IsArchiveProblem(ex)) { await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false); return 1; } } }