From ff73c72b0ea6f5bedb6542534396b71017d5e042 Mon Sep 17 00:00:00 2001 From: Harvey Tindall Date: Thu, 21 Dec 2023 17:27:28 +0000 Subject: [PATCH] backups: add -restore cli argument --- args.go | 4 ++++ daemon.go | 27 +++++++++++++++++++++++++++ main.go | 4 ++++ 3 files changed, 35 insertions(+) diff --git a/args.go b/args.go index 398c2a4..e7eb6f3 100644 --- a/args.go +++ b/args.go @@ -23,6 +23,7 @@ func (app *appContext) loadArgs(firstCall bool) { HOST = flag.String("host", "", "alternate address to host web ui on.") PORT = flag.Int("port", 0, "alternate port to host web ui on.") flag.IntVar(PORT, "p", 0, "SHORTHAND") + _LOADBAK = flag.String("restore", "", "path to database backup to restore.") DEBUG = flag.Bool("debug", false, "Enables debug logging.") PPROF = flag.Bool("pprof", false, "Exposes pprof profiler on /debug/pprof.") SWAGGER = flag.Bool("swagger", false, "Enable swagger at /swagger/index.html") @@ -41,6 +42,9 @@ func (app *appContext) loadArgs(firstCall bool) { if *PPROF { os.Setenv("PPROF", "1") } + if *_LOADBAK != "" { + LOADBAK = *_LOADBAK + } } if os.Getenv("SWAGGER") == "1" { diff --git a/daemon.go b/daemon.go index 2a2cc8a..10f01c9 100644 --- a/daemon.go +++ b/daemon.go @@ -203,6 +203,33 @@ func (app *appContext) makeBackup() (fileDetails CreateBackupDTO) { return } +func (app *appContext) loadPendingBackup() { + if LOADBAK == "" { + return + } + oldPath := filepath.Join(app.dataPath, "db-pre-"+filepath.Base(LOADBAK)) + app.info.Printf("Moving existing database to \"%s\"\n", oldPath) + err := os.Rename(app.storage.db_path, oldPath) + if err != nil { + app.err.Fatalf("Failed to move existing database: %v\n", err) + } + + app.ConnectDB() + defer app.storage.db.Close() + + f, err := os.Open(LOADBAK) + if err != nil { + app.err.Fatalf("Failed to open backup file \"%s\": %v\n", LOADBAK, err) + } + err = app.storage.db.Badger().Load(f, 256) + f.Close() + if err != nil { + app.err.Fatalf("Failed to restore backup file \"%s\": %v\n", LOADBAK, err) + } + app.info.Printf("Restored backup \"%s\".", LOADBAK) + LOADBAK = "" +} + func (app *appContext) clearActivities() { app.debug.Println("Housekeeping: Cleaning up Activity log...") keepCount := app.config.Section("activity_log").Key("keep_n_records").MustInt(1000) diff --git a/main.go b/main.go index 69331d3..52ca32f 100644 --- a/main.go +++ b/main.go @@ -56,6 +56,8 @@ var ( commit string buildTimeUnix string builtBy string + _LOADBAK *string + LOADBAK = "" ) var temp = func() string { @@ -355,8 +357,10 @@ func start(asDaemon, firstCall bool) { } app.storage.db_path = filepath.Join(app.dataPath, "db") + app.loadPendingBackup() app.ConnectDB() defer app.storage.db.Close() + // Read config-base for settings on web. app.configBasePath = "config-base.json" configBase, _ := fs.ReadFile(localFS, app.configBasePath)