-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreadConfig.go
76 lines (69 loc) · 2.28 KB
/
readConfig.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package main
import (
"encoding/json"
"encoding/xml"
"fmt"
"os"
mapset "github.com/deckarep/golang-set/v2"
)
// readConfigXML takes the hostname and config file and dumps a data-cli.json representation for further use
func readConfigXml(hostname string, configFile string, dataFilename string) {
var err error
var localDeviceId string
config := Configuration{}
fileContent, err := readFile(configFile)
if err != nil {
log.Fatal().Msgf("cannot read %s: %s", configFile, err)
}
err = xml.Unmarshal(fileContent, &config)
if err != nil {
log.Fatal().Msgf("cannot unmarshall config.xml: %v", err)
}
// update the devices names in folders
devicesFound := mapset.NewSet[string]() // unique set of devices found in the folders
for _, folder := range config.Folder {
for i, device := range folder.Device {
// find the appropraite device name
for _, knownDevice := range config.Device {
// found matching device ID in devices
if device.ID == knownDevice.ID {
folder.Device[i].Name = knownDevice.Name
}
// attempt to set the ID of the device if names match
if hostname == knownDevice.Name {
localDeviceId = knownDevice.ID
}
devicesFound.Add(knownDevice.Name)
}
}
}
if localDeviceId == "" {
log.Fatal().Msgf("could not match the provided device name %s with known devices in the config file. Found device names: %v", hostname, devicesFound)
}
writeConfigToFile(fmt.Sprintf("%s %s", hostname, localDeviceId), config, dataFilename)
}
func writeConfigToFile(deviceKey string, config Configuration, dataFilename string) {
var err error
dataToWrite := make(dataJsonT)
data, err := readFile(dataFilename)
if err != nil {
// no data file, create new one
log.Info().Msgf("no %s file", dataFilename)
} else {
// unmarshall content and update with new config
err = json.Unmarshal(data, &dataToWrite)
if err != nil {
log.Fatal().Msgf("cannot unmarshal %s: %s", dataFilename, err)
}
}
dataToWrite[deviceKey] = config.Folder
dataToWriteJson, err := json.Marshal(dataToWrite)
if err != nil {
log.Fatal().Msgf("cannot marshal data for %s: %s", dataFilename, err)
}
err = os.WriteFile(dataFilename, dataToWriteJson, 0644)
if err != nil {
log.Fatal().Msgf("cannot write %s: %s", dataFilename, err)
}
log.Info().Msgf("wrote %s file", dataFilename)
}