From 6c32ff3af3ff1c943a05c68159ebc90a4bf73367 Mon Sep 17 00:00:00 2001 From: wgroeneveld Date: Tue, 14 Mar 2023 20:45:49 +0100 Subject: [PATCH] create .restic and config files if not existing, with default values --- restic/config.go | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/restic/config.go b/restic/config.go index 9b877a0..7a03ba9 100644 --- a/restic/config.go +++ b/restic/config.go @@ -6,6 +6,7 @@ import ( "fmt" "github.com/rs/zerolog/log" "os" + "path/filepath" "time" ) @@ -29,23 +30,23 @@ func IsDev() bool { } func PasswordFile() string { - return configDir + "password.txt" + return filepath.Join(configDir, "password.txt") } func LogFile() string { - return configDir + "log.txt" + return filepath.Join(configDir, "log.txt") } func ExcludeFile() string { - return configDir + "excludes.txt" + return filepath.Join(configDir, "excludes.txt") } func ConfigFile() string { - return configDir + "config.json" + return filepath.Join(configDir, "config.json") } func (cnf *Config) MountDir() string { - return configDir + "mnt" + return filepath.Join(configDir, "mnt") } func (cnf *Config) CreateMountDirIfDoesntExist() error { @@ -55,13 +56,25 @@ func (cnf *Config) CreateMountDirIfDoesntExist() error { return nil } +func defaultConfig() *Config { + return &Config{ + BackupTimeInHours: DefaultBackupTimeInHours, + Backup: home, + Repository: os.TempDir(), + } +} + func ReadConfig() (*Config, error) { confData, err := os.ReadFile(ConfigFile()) + conf := &Config{} + if err != nil { - return nil, fmt.Errorf("No config.json found: %w", err) + log.Warn().Err(err).Msg("No config.json found, writing default") + conf = defaultConfig() + confData, _ := json.Marshal(conf) + os.WriteFile(ConfigFile(), confData, os.ModePerm) } - conf := &Config{} err = json.Unmarshal(confData, conf) if err != nil { return nil, fmt.Errorf("config.json malformed JSON: %w", err) @@ -75,5 +88,12 @@ func ReadConfig() (*Config, error) { conf.BackupTimeInHours = DefaultBackupTimeInHours } + if _, err := os.Stat(ExcludeFile()); os.IsNotExist(err) { + os.WriteFile(ExcludeFile(), []byte(""), os.ModePerm) + } + if _, err := os.Stat(PasswordFile()); os.IsNotExist(err) { + os.WriteFile(PasswordFile(), []byte(""), os.ModePerm) + } + return conf, nil }