diff --git a/config/parser.go b/config/parser.go index ea79923..8ebbe0b 100644 --- a/config/parser.go +++ b/config/parser.go @@ -3,7 +3,6 @@ package config import ( "encoding/json" "io/ioutil" - "path/filepath" "sync" "github.com/ooni/probe-cli/utils" @@ -14,7 +13,7 @@ import ( func ReadConfig(path string) (*Config, error) { b, err := ioutil.ReadFile(path) if err != nil { - return nil, errors.Wrap(err, "reading file") + return nil, err } c, err := ParseConfig(b) @@ -93,7 +92,7 @@ func (c *Config) Default() error { return err } - c.path = filepath.Join(home, "config.json") + c.path = utils.ConfigPath(home) return nil } diff --git a/ooni.go b/ooni.go index df2c7a9..c7a7125 100644 --- a/ooni.go +++ b/ooni.go @@ -4,11 +4,11 @@ import ( "io/ioutil" "os" "path" - "path/filepath" "github.com/apex/log" "github.com/jmoiron/sqlx" "github.com/ooni/probe-cli/config" + "github.com/ooni/probe-cli/internal/bindata" "github.com/ooni/probe-cli/internal/database" "github.com/ooni/probe-cli/internal/legacy" "github.com/ooni/probe-cli/internal/onboard" @@ -100,7 +100,7 @@ func (c *Context) Init() error { c.Config, err = config.ReadConfig(c.configPath) } else { log.Debug("Reading default config file") - c.Config, err = ReadDefaultConfigPaths(c.Home) + c.Config, err = InitDefaultConfig(c.Home) } if err != nil { return err @@ -144,21 +144,36 @@ func MaybeInitializeHome(home string) error { return nil } -// ReadDefaultConfigPaths from common locations. -func ReadDefaultConfigPaths(home string) (*config.Config, error) { - var paths = []string{ - filepath.Join(home, "config.json"), - } - for _, path := range paths { - if _, err := os.Stat(path); err == nil { - c, err := config.ReadConfig(path) +// InitDefaultConfig reads the config from common locations or creates it if +// missing. +func InitDefaultConfig(home string) (*config.Config, error) { + var ( + err error + c *config.Config + configPath = utils.ConfigPath(home) + ) + + c, err = config.ReadConfig(configPath) + if err != nil { + if os.IsNotExist(err) { + log.Debugf("writing default config to %s", configPath) + var data []byte + data, err = bindata.Asset("data/default-config.json") if err != nil { return nil, err } - return c, nil + err = ioutil.WriteFile( + configPath, + data, + 0644, + ) + if err != nil { + return nil, err + } + return InitDefaultConfig(home) } + return nil, err } - // Run from the default config - return config.ReadConfig(paths[0]) + return c, nil } diff --git a/utils/paths.go b/utils/paths.go index 63ce079..c4be216 100644 --- a/utils/paths.go +++ b/utils/paths.go @@ -20,6 +20,11 @@ func RequiredDirs(home string) []string { return requiredDirs } +// ConfigPath returns the default path to the config file +func ConfigPath(home string) string { + return filepath.Join(home, "config.json") +} + // GeoIPDir returns the geoip data dir for the given OONI Home func GeoIPDir(home string) string { return filepath.Join(home, "geoip")