package config import ( "bytes" "encoding/json" "log" "os" "path/filepath" "slices" "gitlab.hamburg.ccc.de/ccchh/spaceapid/types" ) const ( envConfigPath = "CONFIG_PATH" ) // getConfigPath gets the spaceapid configuration from the respective environment variables func getConfigPath() string { // JSON template path configPath, ok := os.LookupEnv(envConfigPath) if !ok || configPath == "" { log.Fatalln("Could not retrieve", envConfigPath, "env variable or variable is empty") } // Save as absolute path absConfigPath, err := filepath.Abs(configPath) if err != nil { log.Fatalln("Failed converting", configPath, "to absolute path:", err) } return absConfigPath } // ParseConfiguration returns the config from file func ParseConfiguration() (conf SpaceapidConfig) { log.Println("Parsing configuration file") // Read file file, err := os.ReadFile(getConfigPath()) if err != nil { log.Fatalln("Failed reading file:", err) } // Parse JSON dec := json.NewDecoder(bytes.NewReader(file)) dec.DisallowUnknownFields() err = dec.Decode(&conf) if err != nil { log.Fatalln("Could not parse spaceapid config file:", err) } // Check if compatible with v14 if !slices.Contains(conf.Response.APICompatibility, "14") { log.Fatalln("Provided file doesn't specify compatibility with API version 14") } // Initialise fields for environment sensors conf.Response.Sensors = make(map[string][]types.EnvironmentSensor) for key, sensorConfigs := range conf.Dynamic.Sensors { conf.Response.Sensors[key] = make([]types.EnvironmentSensor, len(sensorConfigs)) for i, sensorConfig := range sensorConfigs { conf.Response.Sensors[key][i] = sensorConfig.SensorData } } return }