package cmd import ( "fmt" "log" "os" "path/filepath" "gitea.nehmer.net/torben/dyndns/service" "gitea.nehmer.net/torben/dyndns/webapi" "github.com/spf13/cobra" "github.com/spf13/viper" ) var ConfigDir string var rootCmd = &cobra.Command{ Use: "dyndns", Short: "Go DynDNS Server", Long: `A DynDNS Server implementation in Go, requires both an NFTable Firewall and a properly configured Bind DNS Server.`, } func init() { cobra.OnInitialize(initConfig) rootCmd.PersistentFlags().StringVarP(&ConfigDir, "config-dir", "c", ".", "base configuration directory, defaults to .") } func Exec() { if err := os.Chdir(ConfigDir); err != nil { log.Fatalf("Could not change to directory %s: %v", ConfigDir, err) } if err := rootCmd.Execute(); err != nil { log.Fatalf("Failed to execute command: %v", err) } } func sanitizeConfigDir() { var err error if ConfigDir, err = filepath.Abs(ConfigDir); err != nil { cobra.CheckErr(fmt.Sprintf("path is invalid: %v", err)) } log.Printf("Using configuration directory %s", ConfigDir) } func initConfig() { sanitizeConfigDir() viper.SetConfigName("conf.yml") viper.SetConfigType("yaml") viper.AddConfigPath(ConfigDir) if err := viper.ReadInConfig(); err != nil { if _, ok := err.(viper.ConfigFileNotFoundError); ok { log.Println("Could not find configfile, using defaults") } else { cobra.CheckErr(fmt.Sprintf("configuration is invalid: %s", err)) } } viper.Set("ConfigDir", ConfigDir) log.Printf("Configuration in use: %v", viper.AllSettings()) } func setAllConfigDefaults() { service.SetConfigDefaults() webapi.SetConfigDefaults() }