118 lines
2.3 KiB
Go
118 lines
2.3 KiB
Go
package main
|
|
|
|
import (
|
|
// Standard
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"slices"
|
|
"strings"
|
|
)
|
|
|
|
type Config struct {
|
|
Network struct {
|
|
Address string
|
|
Port int
|
|
}
|
|
|
|
Logging struct {
|
|
URL string
|
|
System string
|
|
Instance string
|
|
LogDir string
|
|
}
|
|
|
|
Devices []Device
|
|
|
|
filename string
|
|
}
|
|
|
|
type Device struct {
|
|
ID string
|
|
Name string
|
|
Address string
|
|
Port int
|
|
Username string
|
|
Password string
|
|
Timeout int
|
|
}
|
|
|
|
func readConfig() (config Config, err error) {
|
|
var configData []byte
|
|
configData, err = os.ReadFile(flagConfig)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
err = json.Unmarshal(configData, &config)
|
|
config.filename = flagConfig
|
|
return
|
|
}
|
|
|
|
func (cfg *Config) UpdateDevice(deviceToUpdate Device) (dev Device, err error) { // {{{
|
|
i := slices.IndexFunc(cfg.Devices, func(d Device) bool {
|
|
return d.ID == deviceToUpdate.ID
|
|
})
|
|
|
|
if i > -1 {
|
|
dev = cfg.Devices[i]
|
|
}
|
|
|
|
if strings.TrimSpace(deviceToUpdate.Name) == "" {
|
|
err = fmt.Errorf("Name can't be empty")
|
|
return
|
|
}
|
|
if strings.TrimSpace(deviceToUpdate.Address) == "" {
|
|
err = fmt.Errorf("Address can't be empty")
|
|
return
|
|
}
|
|
if strings.TrimSpace(deviceToUpdate.Username) == "" {
|
|
err = fmt.Errorf("Username can't be empty")
|
|
return
|
|
}
|
|
if deviceToUpdate.Port < 1 || deviceToUpdate.Port > 65535 {
|
|
err = fmt.Errorf("Invalid port")
|
|
return
|
|
}
|
|
|
|
dev.Name = strings.TrimSpace(deviceToUpdate.Name)
|
|
dev.Address = strings.TrimSpace(strings.ToLower(deviceToUpdate.Address))
|
|
dev.Port = deviceToUpdate.Port
|
|
dev.Username = strings.TrimSpace(deviceToUpdate.Username)
|
|
|
|
// TODO - Should be configurable...
|
|
if dev.Timeout == 0 {
|
|
dev.Timeout = 10
|
|
}
|
|
|
|
// Device not found - create it!
|
|
if i == -1 {
|
|
if strings.TrimSpace(deviceToUpdate.Password) == "" {
|
|
err = fmt.Errorf("Password can't be empty")
|
|
return
|
|
}
|
|
dev.ID = deviceToUpdate.ID
|
|
dev.Password = strings.TrimSpace(deviceToUpdate.Password)
|
|
cfg.Devices = append(cfg.Devices, dev)
|
|
} else {
|
|
if deviceToUpdate.Password != "" {
|
|
dev.Password = strings.TrimSpace(deviceToUpdate.Password)
|
|
}
|
|
cfg.Devices[i] = dev
|
|
}
|
|
|
|
j, _ := json.Marshal(cfg)
|
|
err = os.WriteFile(cfg.filename, j, 0600)
|
|
|
|
return
|
|
} // }}}
|
|
func (cfg *Config) DeleteDevice(devID string) (err error) { // {{{
|
|
cfg.Devices = slices.DeleteFunc(cfg.Devices, func(d Device) bool {
|
|
return d.ID == devID
|
|
})
|
|
|
|
j, _ := json.Marshal(cfg)
|
|
err = os.WriteFile(cfg.filename, j, 0600)
|
|
|
|
return
|
|
} // }}}
|