10 common "github.com/iotbzh/xds-common/golib"
13 type SyncThingConf struct {
14 BinDir string `json:"binDir"`
15 Home string `json:"home"`
16 GuiAddress string `json:"gui-address"`
17 GuiAPIKey string `json:"gui-apikey"`
20 type FileConfig struct {
21 HTTPPort string `json:"httpPort"`
22 LogsDir string `json:"logsDir"`
23 XDSAPIKey string `json:"xds-apikey"`
24 SThgConf *SyncThingConf `json:"syncthing"`
27 // getConfigFromFile reads configuration from a config file.
28 // Order to determine which config file is used:
29 // 1/ from command line option: "--config myConfig.json"
30 // 2/ $HOME/.xds/agent/agent-config.json file
31 // 3/ <current_dir>/agent-config.json file
32 // 4/ <executable dir>/agent-config.json file
34 func updateConfigFromFile(c *Config, confFile string) (*FileConfig, error) {
36 searchIn := make([]string, 0, 3)
38 searchIn = append(searchIn, confFile)
40 if usr, err := user.Current(); err == nil {
41 searchIn = append(searchIn, path.Join(usr.HomeDir, ".xds", "agent", "agent-config.json"))
44 searchIn = append(searchIn, "/etc/xds-agent/agent-config.json")
47 ee, _ := os.Executable()
48 exeAbsPath, err := filepath.Abs(ee)
50 exePath, err = filepath.EvalSymlinks(exeAbsPath)
52 exePath = filepath.Dir(ee)
54 exePath = filepath.Dir(exeAbsPath)
57 searchIn = append(searchIn, path.Join(exePath, "agent-config.json"))
60 for _, p := range searchIn {
61 if _, err := os.Stat(p); err == nil {
66 // Use default settings
69 // Read config file when existing
71 c.Log.Infof("Use config file: %s", *cFile)
73 // TODO move on viper package to support comments in JSON and also
74 // bind with flags (command line options)
75 // see https://github.com/spf13/viper#working-with-flags
77 fd, _ := os.Open(*cFile)
79 if err := json.NewDecoder(fd).Decode(&fCfg); err != nil {
84 // Support environment variables (IOW ${MY_ENV_VAR} syntax) in agent-config.json
88 if fCfg.SThgConf != nil {
89 vars = append(vars, &fCfg.SThgConf.Home, &fCfg.SThgConf.BinDir)
91 for _, field := range vars {
93 *field, err = common.ResolveEnvVar(*field)
99 // Config file settings overwrite default config
100 if fCfg.HTTPPort != "" {
101 c.HTTPPort = fCfg.HTTPPort
104 // Set default apikey
105 // FIXME - rework with dynamic key
106 if fCfg.XDSAPIKey == "" {
107 fCfg.XDSAPIKey = "1234abcezam"