cmd/weimar/root.go (view raw)
1package main
2
3import (
4 "fmt"
5 "log/slog"
6 "os"
7 "strings"
8
9 "github.com/spf13/cobra"
10 "github.com/spf13/viper"
11)
12
13var cfgFile string
14
15var rootCmd = &cobra.Command{
16 Use: "weimar",
17 Short: "Self-hosted media repository for small groups",
18 Long: `weimar is a single-binary media repository for home servers.
19Store, tag, and browse memes and group-interest images with friends.`,
20 PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
21 return initConfig()
22 },
23 SilenceUsage: true,
24 SilenceErrors: true,
25}
26
27func Execute() error {
28 return rootCmd.Execute()
29}
30
31func init() {
32 rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "path to config file (default ./weimar.toml)")
33 rootCmd.PersistentFlags().String("log-level", "info", "log level (debug, info, warn, error)")
34 viper.BindPFlag("log-level", rootCmd.PersistentFlags().Lookup("log-level"))
35}
36
37func initConfig() error {
38 if cfgFile != "" {
39 viper.SetConfigFile(cfgFile)
40 } else {
41 viper.AddConfigPath(".")
42 viper.SetConfigName("weimar")
43 viper.SetConfigType("toml")
44 }
45
46 viper.SetEnvPrefix("WEIMAR")
47 viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
48 viper.AutomaticEnv()
49
50 if err := viper.ReadInConfig(); err != nil {
51 if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
52 return fmt.Errorf("reading config: %w", err)
53 }
54 }
55
56 setDefaults()
57
58 level := slog.LevelInfo
59 switch strings.ToLower(viper.GetString("log-level")) {
60 case "debug":
61 level = slog.LevelDebug
62 case "warn":
63 level = slog.LevelWarn
64 case "error":
65 level = slog.LevelError
66 }
67 slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: level})))
68
69 return nil
70}
71
72func setDefaults() {
73 viper.SetDefault("server.host", "0.0.0.0")
74 viper.SetDefault("server.port", 8080)
75 viper.SetDefault("database.path", "./data/weimar.db")
76 viper.SetDefault("storage.path", "./data/images")
77 viper.SetDefault("upload.max_size_mb", 50)
78 viper.SetDefault("upload.rate_limit_per_minute", 0)
79 viper.SetDefault("auth.allow_registration", true)
80}