@@ -7,12 +7,35 @@ import (
77 "halsecur/cli/homeAssistant"
88 "halsecur/cli/utils"
99 "os"
10+ "strconv"
11+ "strings"
1012 "time"
1113
14+ "github.com/spf13/cast"
1215 "github.com/spf13/cobra"
1316 "github.com/spf13/viper"
1417)
1518
19+ func getIntSlice (key string ) []int {
20+ raw := viper .Get (key )
21+
22+ if slice , err := cast .ToIntSliceE (raw ); err == nil && len (slice ) > 0 {
23+ return slice
24+ }
25+
26+ str := viper .GetString (key )
27+ if str == "" {
28+ return []int {}
29+ }
30+ var result []int
31+ for _ , s := range strings .Split (str , "," ) {
32+ if n , err := strconv .Atoi (strings .TrimSpace (s )); err == nil {
33+ result = append (result , n )
34+ }
35+ }
36+ return result
37+ }
38+
1639func init () {
1740 var (
1841 mqttServerName string
@@ -56,7 +79,7 @@ func init() {
5679 mqttPassword = viper .GetString (ArgMqttPasswordName )
5780 mqttTelePeriod = viper .GetDuration (ArgMqttTelePeriodName )
5881 mqttTelePeriodFast = viper .GetDuration (ArgMqttTelePeriodFastName )
59- devicePorts = viper . GetIntSlice (ArgDevicePortsName )
82+ devicePorts = getIntSlice (ArgDevicePortsName )
6083 doorStatusSupported = viper .GetBool (ArgDoorStatusSupported )
6184
6285 autoTokenRefresh := viper .GetBool (ArgNameAutoLogin )
@@ -68,11 +91,16 @@ func init() {
6891 cli .Log .Warnf ("%s parameter empty. This might be wrong." , ArgDevicePortsName )
6992 }
7093
71- // Store token in persistent config
94+ // Store token in persistent
7295 defer func () {
7396 viper .Set (ArgNameToken , token )
7497 viper .Set (ArgNameLastLoginTimeStamp , lastLoginTime )
75- err := viper .WriteConfig ()
98+ _ , err := os .Stat ("config.yaml" )
99+ if os .IsNotExist (err ) {
100+ err = viper .WriteConfigAs ("config.yaml" )
101+ } else {
102+ err = viper .WriteConfig ()
103+ }
76104 if err != nil {
77105 cli .Log .Errorf ("Failed to save new configuration. %v" , err )
78106 }
@@ -124,4 +152,10 @@ func init() {
124152 cli .Log .Fatalf ("failed to bind flags: %v" , err )
125153 os .Exit (1 )
126154 }
155+
156+ // ENV support
157+ viper .SetEnvPrefix ("HALSECUR" )
158+ viper .SetEnvKeyReplacer (strings .NewReplacer ("." , "_" ))
159+ viper .AutomaticEnv ()
160+
127161}
0 commit comments