diff --git a/config/config.go b/config/config.go index ef9edff..fc5ea1c 100644 --- a/config/config.go +++ b/config/config.go @@ -7,6 +7,7 @@ import ( "log" "os" "os/signal" + "path/filepath" "syscall" ) @@ -16,6 +17,7 @@ type Configuration struct { PulseSink string `json:"-"` DeviceName string `json:"-"` exitsSignals chan os.Signal + baseDir string } var Config = &Configuration{ @@ -24,28 +26,46 @@ var Config = &Configuration{ DeviceUUID: uuid.NewString(), } -func (c *Configuration) Load() { - data, err := ioutil.ReadFile(c.DeviceName + "/config.json") +func (c *Configuration) Load(baseDir string) error { + if baseDir == "" { + var err error + baseDir, err = os.Getwd() + if err != nil { + return err + } + } + + c.baseDir = baseDir + configFilePath := filepath.Join(c.baseDir, c.DeviceName, "/config.json") + data, err := ioutil.ReadFile(configFilePath) if err != nil || json.Unmarshal(data, &c) != nil { - log.Printf("%s is not valid - at new file will be created at program exit\n", c.DeviceName+"/config.json") + log.Printf("%s is not valid - a new file will be created at program exit\n", configFilePath) } c.exitsSignals = make(chan os.Signal, 1) signal.Notify(c.exitsSignals, syscall.SIGINT, syscall.SIGTERM) go func() { <-c.exitsSignals - c.Store() + err := c.Store() + if err != nil { + os.Exit(1) + } os.Exit(0) }() + + return nil } -func (c *Configuration) Store() { +func (c *Configuration) Store() error { data, err := json.Marshal(&c) if err != nil { - log.Printf("Warning: impossible to marshal configuration in json") + log.Printf("Warning: impossible to marshal configuration in json\n") + return err } - err = ioutil.WriteFile(c.DeviceName+"/config.json", data, 0660) + configFilePath := filepath.Join(c.baseDir, c.DeviceName, "/config.json") + err = ioutil.WriteFile(configFilePath, data, 0660) if err != nil { - log.Printf("Warning : impossible to store config file %s \n", c.DeviceName+"/config.json") + log.Printf("Warning : impossible to store config file %s \n", configFilePath) } + return err } diff --git a/main.go b/main.go index 9a72284..34c3223 100644 --- a/main.go +++ b/main.go @@ -21,14 +21,16 @@ import ( func main() { var ifName string var delay int64 + var configurationBaseDir string + flag.StringVar(&configurationBaseDir, "c", ".", "Configuration base directory (default to current directory)") flag.StringVar(&config.Config.DeviceName, "n", "goplay", "Specify device name") flag.StringVar(&ifName, "i", "eth0", "Specify interface") flag.Int64Var(&delay, "delay", 0, "Specify hardware delay in ms") flag.StringVar(&config.Config.PulseSink, "sink", config.Config.PulseSink, "Specify Pulse Audio Sink - Linux only") flag.Parse() // after declaring flags we need to call it - config.Config.Load() + config.Config.Load(configurationBaseDir) defer config.Config.Store() globals.ErrLog = log.New(os.Stderr, "Error:", log.LstdFlags|log.Lshortfile|log.Lmsgprefix)