blob: e0ee0d696695f21c016ae6c212fde7e25c090042 (
plain)
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
// Package config implements functions for saving a struct to a file
// It then provides functions to later read it such that we can restore the same struct
package config
import (
"encoding/json"
"log/slog"
"os"
"path"
"herkulessi.de/git/eduvpn-common/internal/atomicfile"
"herkulessi.de/git/eduvpn-common/internal/config/v2"
"herkulessi.de/git/eduvpn-common/internal/discovery"
)
const stateFile = "state.json"
// Config represents the config state file
type Config struct {
directory string
// V2 indicates we are version 2
V2 *v2.V2
}
func (c *Config) filename() string {
return path.Join(c.directory, stateFile)
}
// Discovery gets the discovery list from the state file
func (c *Config) Discovery() *discovery.Discovery {
return &c.V2.Discovery
}
// HasSecureInternet returns whether or not the configuration has a secure internet server
func (c *Config) HasSecureInternet() bool {
return c.V2.HasSecureInternet()
}
// Save saves the state file to disk
func (c *Config) Save() error {
if err := os.MkdirAll(c.directory, 0o700); err != nil {
return err
}
join := Versioned{V2: c.V2}
cfg, err := json.Marshal(join)
if err != nil {
return err
}
if err = atomicfile.WriteFile(c.filename(), cfg, 0o600); err != nil {
return err
}
return nil
}
// Load loads the state file from disk
func (c *Config) Load() error {
bts, err := os.ReadFile(c.filename())
if err != nil {
return err
}
var buf Versioned
if err = json.Unmarshal(bts, &buf); err != nil {
return err
}
c.V2 = buf.V2
return nil
}
// Versioned is the final top-level state file that is written to disk
type Versioned struct {
// V2 is the version 2 state file
V2 *v2.V2 `json:"v2,omitempty"`
}
// NewFromDirectory creates a new config struct from a directory
// It does this by loading the JSON file from disk
func NewFromDirectory(dir string) *Config {
cfg := Config{
directory: dir,
}
err := cfg.Load()
if err != nil {
slog.Debug("failed to load configuration", "error", err)
}
if cfg.V2 == nil {
cfg.V2 = &v2.V2{}
}
return &cfg
}
|