Auto start Syncthing and Syncthing-inotify.
[src/xds/xds-server.git] / lib / xdsconfig / config.go
1 package xdsconfig
2
3 import (
4         "fmt"
5
6         "os"
7
8         "github.com/Sirupsen/logrus"
9         "github.com/codegangsta/cli"
10 )
11
12 // Config parameters (json format) of /config command
13 type Config struct {
14         Version       string        `json:"version"`
15         APIVersion    string        `json:"apiVersion"`
16         VersionGitTag string        `json:"gitTag"`
17         Builder       BuilderConfig `json:"builder"`
18         Folders       FoldersConfig `json:"folders"`
19
20         // Private (un-exported fields in REST GET /config route)
21         FileConf     FileConfig     `json:"-"`
22         WebAppDir    string         `json:"-"`
23         HTTPPort     string         `json:"-"`
24         ShareRootDir string         `json:"-"`
25         Log          *logrus.Logger `json:"-"`
26 }
27
28 // Config default values
29 const (
30         DefaultAPIVersion = "1"
31         DefaultPort       = "8000"
32         DefaultShareDir   = "/mnt/share"
33 )
34
35 // Init loads the configuration on start-up
36 func Init(cliCtx *cli.Context, log *logrus.Logger) (*Config, error) {
37         var err error
38
39         // Define default configuration
40         c := Config{
41                 Version:       cliCtx.App.Metadata["version"].(string),
42                 APIVersion:    DefaultAPIVersion,
43                 VersionGitTag: cliCtx.App.Metadata["git-tag"].(string),
44                 Builder:       BuilderConfig{},
45                 Folders:       FoldersConfig{},
46
47                 WebAppDir:    "webapp/dist",
48                 HTTPPort:     DefaultPort,
49                 ShareRootDir: DefaultShareDir,
50                 Log:          log,
51         }
52
53         // config file settings overwrite default config
54         err = updateConfigFromFile(&c, cliCtx.GlobalString("config"))
55         if err != nil {
56                 return nil, err
57         }
58
59         // Update location of shared dir if needed
60         if !dirExists(c.ShareRootDir) {
61                 if err := os.MkdirAll(c.ShareRootDir, 0770); err != nil {
62                         return nil, fmt.Errorf("No valid shared directory found: %v", err)
63                 }
64         }
65         c.Log.Infoln("Share root directory: ", c.ShareRootDir)
66
67         if c.FileConf.LogsDir != "" && !dirExists(c.FileConf.LogsDir) {
68                 if err := os.MkdirAll(c.FileConf.LogsDir, 0770); err != nil {
69                         return nil, fmt.Errorf("Cannot create logs dir: %v", err)
70                 }
71         }
72         c.Log.Infoln("Logs directory: ", c.FileConf.LogsDir)
73
74         return &c, nil
75 }
76
77 func dirExists(path string) bool {
78         _, err := os.Stat(path)
79         if os.IsNotExist(err) {
80                 return false
81         }
82         return true
83 }