config.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package core
  2. import (
  3. "fmt"
  4. "github.com/charmbracelet/log"
  5. "github.com/spf13/viper"
  6. "github.com/sstallion/go-hid"
  7. "os"
  8. "path/filepath"
  9. )
  10. func getConfigDir() string {
  11. return "/etc/"
  12. }
  13. // Check is config present in $HOME/.config/lianlinux, if not - create.
  14. func isConfigPresent() string {
  15. // Set the config file name and path
  16. configFileName := "config.json"
  17. configFilePath := filepath.Join(getConfigDir(), "lianlinux")
  18. log.Debugf("configFilePath %s configFileName %s", configFilePath, configFileName)
  19. viper.SetConfigType("json")
  20. // Set the config file name and path
  21. viper.SetConfigName(configFileName)
  22. viper.AddConfigPath(configFilePath)
  23. viper.SetDefault("current", "rainbow")
  24. viper.SetDefault("rgb", map[string]int{"r": 0, "g": 0, "b": 0})
  25. // Check if the config file already exists
  26. if _, err := os.Stat(filepath.Join(configFilePath, configFileName)); os.IsNotExist(err) {
  27. // Create the config directory if it doesn't exist
  28. if err := os.MkdirAll(configFilePath, 0755); err != nil {
  29. log.Fatalf("Failed to create config directory: %v", err)
  30. return ""
  31. }
  32. // Create a new config file with default values
  33. if err := viper.SafeWriteConfigAs(filepath.Join(configFilePath, configFileName)); err != nil {
  34. log.Fatalf("Failed to create config file: %v", err)
  35. return ""
  36. }
  37. log.Info(fmt.Sprintf("Config file created at %s", filepath.Join(configFilePath, configFileName)))
  38. } else {
  39. // Read the existing config file
  40. if err := viper.ReadInConfig(); err != nil {
  41. log.Fatalf("Failed to read config file: %v", err)
  42. return ""
  43. }
  44. }
  45. return filepath.Join(configFilePath, configFileName)
  46. }
  47. // Read JSON config
  48. func readConfig() {
  49. viper.SetConfigFile(isConfigPresent())
  50. err := viper.ReadInConfig()
  51. if err != nil {
  52. log.Fatalf("Error reading config file: %s", err)
  53. return
  54. }
  55. }
  56. // Set device light mode by config key "current"
  57. func setConfigLightMode(device hid.DeviceInfo) {
  58. currentMode := viper.Get("current").(string)
  59. rgb := viper.Get("rgb").(map[string]interface{})
  60. rgbArray := []byte{byte(rgb["r"].(float64)), byte(rgb["g"].(float64)), byte(rgb["b"].(float64))}
  61. SetLightMode(device, currentMode, rgbArray...)
  62. }