package cmd import ( "fmt" "log" "os" "strings" "git.bloy.org/mike/hasshelper/web" "github.com/rs/zerolog" "github.com/spf13/cobra" "github.com/spf13/viper" ) var cfgFile string var rootCmd = &cobra.Command{ Use: "hasshelper", Short: "Helper for Home Assistant installations.", Run: rootCmdRun, } func rootCmdRun(cmd *cobra.Command, args []string) { logLevel, err := zerolog.ParseLevel(viper.GetString("loglevel")) zerolog.SetGlobalLevel(logLevel) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } var logger zerolog.Logger if viper.GetString("deployment") == "prod" { logger = zerolog.New(os.Stderr) } else { logger = zerolog.New(zerolog.ConsoleWriter{ Out: os.Stdout, FormatLevel: func(i interface{}) string { return strings.ToUpper(fmt.Sprintf("%-6s|", i)) }, }) } logger = logger.With().Timestamp().Caller().Logger() logger.Info().Str("version", viper.GetString("version")).Msg("HASSHelper startup") exitchan := make(chan bool) web.Run(logger, exitchan) <-exitchan // run the main command until one of the goroutines is done } // Execute will kick off cobra's processing of the root command func Execute() { if err := rootCmd.Execute(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } func init() { rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file (default is $HOME/.config/hasshelper/config.toml)") cobra.OnInitialize(initConfig) const dirName = "hasshelper" var userConfigDir, err = os.UserConfigDir() if err == nil { viper.AddConfigPath( fmt.Sprintf("%s%c%s", userConfigDir, os.PathSeparator, dirName)) } else { log.Println("could not locate user config dir:", err) } viper.AddConfigPath(fmt.Sprintf("/etc%c%s", os.PathSeparator, dirName)) viper.SetConfigName("config.toml") viper.SetEnvPrefix("hasshelper") viper.Set("version", gitVersion) viper.SetDefault("deployment", "prod") viper.SetDefault("loglevel", "info") } func initConfig() { viper.AutomaticEnv() if cfgFile != "" { viper.SetConfigFile(cfgFile) } if err := viper.ReadInConfig(); err != nil { if _, ok := err.(viper.ConfigFileNotFoundError); ok { log.Printf("no config file found. Environment only") } else { log.Fatalf("error reading config file: %v\n", err) } } expected_config := []string{ "deployment", "image_dir", "version", "webserver_port", } for _, key := range expected_config { if !viper.IsSet(key) { fmt.Fprintf(os.Stderr, "Missing configuration value: %s\n", key) os.Exit(1) } } }