package config import ( "encoding/json" "fmt" "os" "path/filepath" "git.cryptic.systems/fh-trier/go-flucky/pkg/types" "github.com/satori/go.uuid" ) var configFilename = "config.json" var humiditiesLogfileName = "humidities.log" var temperatureLogfileName = "temperature.log" func Create(configDir, logDir string, force bool) error { configPath := filepath.Join(configDir, configFilename) humiditiesLogfile := filepath.Join(logDir, humiditiesLogfileName) temperaturLogfile := filepath.Join(logDir, temperatureLogfileName) config := &types.Config{ DeviceID: uuid.NewV4().String(), HumidityLogfile: humiditiesLogfile, TemperatureLogfile: temperaturLogfile, } // If no config file exists, create a new one on the location if !force { if _, err := os.Stat(configPath); !os.IsNotExist(err) { return fmt.Errorf("%v already exists. Use -f to overwrite", configPath) } } if _, err := os.Stat(configPath); os.IsNotExist(err) { err := os.MkdirAll(configDir, os.ModePerm) if err != nil { return fmt.Errorf("Can not create directory: %v", err) } } f, err := os.Create(configPath) if err != nil { return fmt.Errorf("Can not create config: %v", err) } defer f.Close() config.JSONWriter(f) return nil } func DeviceName(deviceName, configDir string) error { cnf, err := Read(configDir) if err != nil { return err } cnf.DeviceName = deviceName err = Write(cnf, configDir) if err != nil { return err } return nil } func DeviceLocation(deviceLocation, configDir string) error { cnf, err := Read(configDir) if err != nil { return err } cnf.DeviceLocation = deviceLocation err = Write(cnf, configDir) if err != nil { return err } return nil } func Read(configDir string) (*types.Config, error) { configPath := filepath.Join(configDir, configFilename) var config types.Config // If no config file exists, return an error if _, err := os.Stat(configPath); os.IsNotExist(err) { return nil, fmt.Errorf("Can not find config %v: %v", configPath, err) } // open config file jsonFile, err := os.Open(configPath) if err != nil { return nil, fmt.Errorf("Can not open file %v: %v", configPath, err) } defer jsonFile.Close() jsonParser := json.NewDecoder(jsonFile) if err := jsonParser.Decode(&config); err != nil { return nil, err } return &config, nil } func Write(config *types.Config, configDir string) error { configPath := filepath.Join(configDir, configFilename) // If no config file exists, return an error if _, err := os.Stat(configPath); os.IsNotExist(err) { return fmt.Errorf("Can not find config %v: %v", configPath, err) } // open config file jsonFile, err := os.Create(configPath) if err != nil { return fmt.Errorf("Can not open file %v: %v", configPath, err) } defer jsonFile.Close() err = config.JSONWriter(jsonFile) if err != nil { return err } return nil }