Device management
This commit is contained in:
parent
5635c2af1a
commit
b9a5437909
6 changed files with 294 additions and 9 deletions
64
config.go
64
config.go
|
|
@ -3,7 +3,10 @@ package main
|
|||
import (
|
||||
// Standard
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
|
|
@ -20,6 +23,8 @@ type Config struct {
|
|||
}
|
||||
|
||||
Devices []Device
|
||||
|
||||
filename string
|
||||
}
|
||||
|
||||
type Device struct {
|
||||
|
|
@ -39,5 +44,64 @@ func readConfig() (config Config, err error) {
|
|||
}
|
||||
|
||||
err = json.Unmarshal(configData, &config)
|
||||
config.filename = flagConfig
|
||||
return
|
||||
}
|
||||
|
||||
func (cfg *Config) UpdateDevice(currentName string, deviceToUpdate Device) (dev Device, err error) {
|
||||
|
||||
i := slices.IndexFunc(cfg.Devices, func(d Device) bool {
|
||||
return strings.TrimSpace(strings.ToLower(d.Name)) == strings.TrimSpace(strings.ToLower(currentName))
|
||||
})
|
||||
|
||||
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(strings.ToLower(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.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
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue