2022-12-29 14:32:48 -05:00
|
|
|
package config
|
|
|
|
|
|
|
|
import (
|
2022-12-29 17:45:57 -05:00
|
|
|
"os"
|
|
|
|
"path"
|
2022-12-29 14:32:48 -05:00
|
|
|
"strings"
|
|
|
|
|
2022-12-29 17:45:57 -05:00
|
|
|
"github.com/pelletier/go-toml/v2"
|
2022-12-29 14:32:48 -05:00
|
|
|
"github.com/spf13/viper"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
StatusOnline int8 = iota
|
|
|
|
StatusOffline = 2
|
|
|
|
StatusNoNewSyncs = 3
|
|
|
|
)
|
|
|
|
|
|
|
|
var VERSION string
|
|
|
|
|
|
|
|
type ServiceStatus int8
|
|
|
|
|
2022-12-29 17:45:57 -05:00
|
|
|
type SystemConfig struct {
|
|
|
|
Type string
|
|
|
|
Config map[string]interface{}
|
|
|
|
}
|
|
|
|
|
2022-12-29 14:32:48 -05:00
|
|
|
type Config struct {
|
2022-12-31 13:00:32 -05:00
|
|
|
Debug bool
|
|
|
|
Log string
|
2022-12-29 14:32:48 -05:00
|
|
|
|
2022-12-29 17:45:57 -05:00
|
|
|
Systems []SystemConfig
|
2022-12-29 14:32:48 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
func Load() (Config, error) {
|
2022-12-29 17:45:57 -05:00
|
|
|
cfgDir, err := os.UserConfigDir()
|
|
|
|
if err != nil {
|
|
|
|
return Config{}, err
|
|
|
|
}
|
|
|
|
homeDir, err := os.UserHomeDir()
|
|
|
|
if err != nil {
|
|
|
|
return Config{}, err
|
|
|
|
}
|
2022-12-31 13:00:32 -05:00
|
|
|
cacheDir, err := os.UserCacheDir()
|
|
|
|
if err != nil {
|
|
|
|
return Config{}, err
|
|
|
|
}
|
2022-12-29 17:45:57 -05:00
|
|
|
|
2022-12-29 14:32:48 -05:00
|
|
|
viper.SetDefault("Debug", "true")
|
2022-12-31 13:00:32 -05:00
|
|
|
viper.SetDefault("Log", path.Join(cacheDir, "gobbs.log"))
|
2022-12-29 14:32:48 -05:00
|
|
|
|
2022-12-29 17:45:57 -05:00
|
|
|
viper.SetConfigName("gobbs")
|
2022-12-29 14:32:48 -05:00
|
|
|
viper.SetConfigType("toml")
|
2022-12-29 17:45:57 -05:00
|
|
|
viper.AddConfigPath(cfgDir)
|
|
|
|
viper.AddConfigPath(homeDir)
|
2022-12-29 14:32:48 -05:00
|
|
|
|
|
|
|
viper.SetEnvPrefix("gobbs")
|
|
|
|
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
|
|
|
viper.AutomaticEnv()
|
|
|
|
|
|
|
|
if err := viper.ReadInConfig(); err != nil {
|
|
|
|
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
|
|
|
|
return Config{}, err
|
2022-12-29 17:45:57 -05:00
|
|
|
} else {
|
|
|
|
return Config{}, nil
|
2022-12-29 14:32:48 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var config Config
|
|
|
|
if err := viper.Unmarshal(&config); err != nil {
|
|
|
|
return Config{}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return config, nil
|
|
|
|
}
|
2022-12-29 17:45:57 -05:00
|
|
|
|
|
|
|
func (cfg *Config) Save() error {
|
|
|
|
cfgFile := viper.ConfigFileUsed()
|
|
|
|
if cfgFile == "" {
|
|
|
|
cfgDir, err := os.UserConfigDir()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
cfgFile = path.Join(cfgDir, "gobbs.toml")
|
|
|
|
}
|
|
|
|
|
|
|
|
fd, err := os.OpenFile(cfgFile, os.O_WRONLY|os.O_CREATE, 0600)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer fd.Close()
|
|
|
|
|
|
|
|
if err := toml.NewEncoder(fd).Encode(cfg); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|