package config import ( "os" "path" "strings" "time" "velvettear/godyn/log" "velvettear/godyn/tools" "github.com/fsnotify/fsnotify" "github.com/spf13/viper" ) // exported function(s) func Initialize() { timestamp := time.Now().UnixMilli() configSpecified := false for index, arg := range os.Args { arg = strings.ToLower(arg) if arg == "-h" || arg == "--"+help { tools.PrintHelp() } if arg == "-y" || arg == "--"+yaml { viper.SetConfigFile(os.Args[index+1]) configSpecified = true continue } if arg == "-c" || arg == "--client" { clientMode = true continue } if arg == "-s" || arg == "--server" { serverMode = true continue } } setDefaults() if !configSpecified { var mode string if serverMode { mode = "server" } else { mode = "client" } viper.SetConfigName(mode + "-config") viper.SetConfigType("yaml") viper.AddConfigPath("$HOME/.config/godyn/") viper.AddConfigPath("$HOME/.config/") workingDirectory, error := os.Getwd() for error == nil && path.Base(workingDirectory) != "godyn" { workingDirectory = path.Dir(workingDirectory) if workingDirectory == "/" { workingDirectory = "." break } } viper.AddConfigPath(workingDirectory) } error := viper.ReadInConfig() if configSpecified && error != nil { log.FatalTimed("encountered an error parsing specified config file '"+viper.ConfigFileUsed()+"'", timestamp, error.Error()) } log.SetDebug(Debug()) log.DebugTimed("parsed config file '"+viper.ConfigFileUsed()+"'", timestamp) viper.OnConfigChange(func(in fsnotify.Event) { log.Info("config file changed") }) viper.WatchConfig() } // unexported function(s) func setDefaults() { // set server defaults viper.SetDefault(serverListen, "localhost") viper.SetDefault(serverPort, 3333) // set client defaults viper.SetDefault(ipProviderUrl, "https://icanhazip.com") viper.SetDefault(interval, 0) // set notification settings viper.SetDefault(notificatonEnabled, false) // set other defaults viper.SetDefault(debug, false) viper.SetDefault(help, false) }