This repository has been archived on 2026-07-15. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
drive/backend/workers/backup.go
Elijah 724d70e58b
Some checks failed
Automated Container Build / build-and-push (push) Failing after 12s
Inital build
2026-05-22 12:29:43 -07:00

48 lines
1.4 KiB
Go

package workers
import (
"fmt"
"log"
"os/exec"
"path/filepath"
"time"
"git.elijahkuntz.com/Elijah/drive/config"
"git.elijahkuntz.com/Elijah/drive/database"
)
// StartBackupWorker runs a periodic SQLite backup task
func StartBackupWorker(cfg *config.Config, db *database.DB) {
ticker := time.NewTicker(24 * time.Hour)
go func() {
for range ticker.C {
runBackup(cfg, db)
}
}()
// Also run one backup 5 minutes after startup if it hasn't been backed up today
time.AfterFunc(5*time.Minute, func() {
runBackup(cfg, db)
})
}
func runBackup(cfg *config.Config, db *database.DB) {
timestamp := time.Now().Format("20060102")
backupFileName := fmt.Sprintf("drive_db_%s.sqlite", timestamp)
backupPath := filepath.Join(cfg.BackupDir, backupFileName)
// We use the sqlite3 CLI for a safe, online backup (it handles WAL mode correctly)
cmd := exec.Command("sqlite3", cfg.DBPath, fmt.Sprintf(".backup '%s'", backupPath))
if err := cmd.Run(); err != nil {
log.Printf("❌ Database backup failed: %v", err)
db.AddAuditLog("backup_failed", err.Error(), "system")
return
}
log.Printf("✅ Database backed up successfully: %s", backupFileName)
db.AddAuditLog("backup_success", backupFileName, "system")
// Optional: Prune old backups (keep last 7 days)
// Not fully implemented here to keep it simple, but would just delete files older than 7d in cfg.BackupDir
}