internal/config.go

199 lines · 5685 bytes

  1package internal
  2
  3import (
  4	"bufio"
  5	"fmt"
  6	"os"
  7	"path/filepath"
  8	"reflect"
  9	"strconv"
 10	"strings"
 11)
 12
 13// CurdConfig struct with field names that match the config keys
 14type CurdConfig struct {
 15	Player                  string `config:"Player"`
 16	SubsLanguage            string `config:"SubsLanguage"`
 17	SubOrDub                string `config:"SubOrDub"`
 18	StoragePath             string `config:"StoragePath"`
 19	PercentageToMarkComplete int    `config:"PercentageToMarkComplete"`
 20	NextEpisodePrompt       bool   `config:"NextEpisodePrompt"`
 21	SkipOp                  bool   `config:"SkipOp"`
 22	SkipEd                  bool   `config:"SkipEd"`
 23	SkipFiller              bool   `config:"SkipFiller"`
 24	SkipRecap               bool   `config:"SkipRecap"`
 25	ScoreOnCompletion       bool   `config:"ScoreOnCompletion"`
 26	SaveMpvSpeed            bool   `config:"SaveMpvSpeed"`
 27	DiscordPresence         bool   `config:"DiscordPresence"`
 28}
 29
 30// LoadConfig reads or creates the config file, adds missing fields, and returns the populated CurdConfig struct
 31func LoadConfig(configPath string) (CurdConfig, error) {
 32	configPath = os.ExpandEnv(configPath) // Substitute environment variables like $HOME
 33
 34	// Check if config file exists
 35	if _, err := os.Stat(configPath); os.IsNotExist(err) {
 36		// Create the config file with default values if it doesn't exist
 37		fmt.Println("Config file not found. Creating default config...")
 38		if err := createDefaultConfig(configPath); err != nil {
 39			return CurdConfig{}, fmt.Errorf("error creating default config file: %v", err)
 40		}
 41	}
 42
 43	// Load the config from file
 44	configMap, err := loadConfigFromFile(configPath)
 45	if err != nil {
 46		return CurdConfig{}, fmt.Errorf("error loading config file: %v", err)
 47	}
 48
 49	// Add missing fields to the config map
 50	updated := false
 51	defaultConfigMap := defaultConfigMap()
 52	for key, defaultValue := range defaultConfigMap {
 53		if _, exists := configMap[key]; !exists {
 54			configMap[key] = defaultValue
 55			updated = true
 56		}
 57	}
 58
 59	// Write updated config back to file if there were any missing fields
 60	if updated {
 61		if err := saveConfigToFile(configPath, configMap); err != nil {
 62			return CurdConfig{}, fmt.Errorf("error saving updated config file: %v", err)
 63		}
 64	}
 65
 66	// Populate the CurdConfig struct from the config map
 67	config := populateConfig(configMap)
 68
 69	return config, nil
 70}
 71
 72// Default configuration values as a map
 73func defaultConfigMap() map[string]string {
 74	return map[string]string{
 75		"Player":                  "mpv",
 76		"StoragePath":             "$HOME/.local/share/curd",
 77		"SubsLanguage":            "english",
 78		"SubOrDub":                "sub",
 79		"PercentageToMarkComplete": "85",
 80		"NextEpisodePrompt":       "false",
 81		"SkipOp":                  "true",
 82		"SkipEd":                  "true",
 83		"SkipFiller":              "true",
 84		"SkipRecap":               "true",
 85		"ScoreOnCompletion":       "true",
 86		"SaveMpvSpeed":            "true",
 87		"DiscordPresence":         "true",
 88	}
 89}
 90
 91// Create a config file with default values in key=value format
 92// Ensure the directory exists before creating the file
 93func createDefaultConfig(path string) error {
 94	defaultConfig := defaultConfigMap()
 95
 96	// Ensure the directory exists
 97	dir := filepath.Dir(path)
 98	if err := os.MkdirAll(dir, 0755); err != nil {
 99		return fmt.Errorf("error creating directory: %v", err)
100	}
101
102	file, err := os.Create(path)
103	if err != nil {
104		return fmt.Errorf("error creating file: %v", err)
105	}
106	defer file.Close()
107
108	writer := bufio.NewWriter(file)
109	for key, value := range defaultConfig {
110		line := fmt.Sprintf("%s=%s\n", key, value)
111		if _, err := writer.WriteString(line); err != nil {
112			return fmt.Errorf("error writing to file: %v", err)
113		}
114	}
115	if err := writer.Flush(); err != nil {
116		return fmt.Errorf("error flushing writer: %v", err)
117	}
118	return nil
119}
120
121// Load config file from disk into a map (key=value format)
122func loadConfigFromFile(path string) (map[string]string, error) {
123	file, err := os.Open(path)
124	if err != nil {
125		return nil, err
126	}
127	defer file.Close()
128
129	configMap := make(map[string]string)
130	scanner := bufio.NewScanner(file)
131
132	for scanner.Scan() {
133		line := strings.TrimSpace(scanner.Text())
134		if line == "" || strings.HasPrefix(line, "#") {
135			continue // Skip empty lines and comments
136		}
137
138		parts := strings.SplitN(line, "=", 2)
139		if len(parts) == 2 {
140			key := strings.TrimSpace(parts[0])
141			value := strings.TrimSpace(parts[1])
142			configMap[key] = value
143		}
144	}
145
146	if err := scanner.Err(); err != nil {
147		return nil, err
148	}
149
150	return configMap, nil
151}
152
153// Save updated config map to file in key=value format
154func saveConfigToFile(path string, configMap map[string]string) error {
155	file, err := os.Create(path)
156	if err != nil {
157		return err
158	}
159	defer file.Close()
160
161	writer := bufio.NewWriter(file)
162	for key, value := range configMap {
163		line := fmt.Sprintf("%s=%s\n", key, value)
164		if _, err := writer.WriteString(line); err != nil {
165			return err
166		}
167	}
168	return writer.Flush()
169}
170
171// Populate the CurdConfig struct from a map
172func populateConfig(configMap map[string]string) CurdConfig {
173	config := CurdConfig{}
174	configValue := reflect.ValueOf(&config).Elem()
175
176	for i := 0; i < configValue.NumField(); i++ {
177		field := configValue.Type().Field(i)
178		tag := field.Tag.Get("config")
179
180		if value, exists := configMap[tag]; exists {
181			fieldValue := configValue.FieldByName(field.Name)
182
183			if fieldValue.CanSet() {
184				switch fieldValue.Kind() {
185				case reflect.String:
186					fieldValue.SetString(value)
187				case reflect.Int:
188					intVal, _ := strconv.Atoi(value)
189					fieldValue.SetInt(int64(intVal))
190				case reflect.Bool:
191					boolVal, _ := strconv.ParseBool(value)
192					fieldValue.SetBool(boolVal)
193				}
194			}
195		}
196	}
197
198	return config
199}