config.go 2.03 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
// Package config handles basic configuration store for the GUI only.
// DFSS configuration is stored in the HOME/.dfss/config.json file
package config

import (
	"encoding/json"
	"io/ioutil"
	"os"
	"os/user"
	"path/filepath"

ElyKar's avatar
ElyKar committed
12 13
	"github.com/spf13/viper"
)
14 15 16

// Config is the structure that will be persisted in the configuration file
type Config struct {
Loïck Bonniot's avatar
Loïck Bonniot committed
17 18
	Email    string `json:"email"`
	Platform string `json:"platform"`
19 20 21 22
}

// Load loads the configuration file into memory.
// If the file does not exist, the configuration will holds default values.
ElyKar's avatar
ElyKar committed
23 24 25 26 27
func Load() {
	// Load config file
	path := GetHomeDir()
	viper.AddConfigPath(GetHomeDir())
	viper.SetConfigName(viper.GetString("filename_config"))
28
	viper.ReadInConfig()
29

ElyKar's avatar
ElyKar committed
30 31 32 33 34 35 36 37
	// Alias for platform
	viper.RegisterAlias("platform_addrport", "platform")

	// Setup file paths
	viper.Set("home_dir", path)
	viper.Set("file_ca", filepath.Join(path, viper.GetString("filename_ca")))
	viper.Set("file_cert", filepath.Join(path, viper.GetString("filename_cert")))
	viper.Set("file_key", filepath.Join(path, viper.GetString("filename_key")))
38
	viper.Set("file_config", filepath.Join(path, viper.GetString("filename_config"))+".json")
39 40

	// Fill virtual-only fields
ElyKar's avatar
ElyKar committed
41 42
	viper.Set("registered", isFileValid(viper.GetString("file_key")))
	viper.Set("authenticated", isFileValid(viper.GetString("file_cert")))
43
	viper.Set("local_port", 9005)
44

45 46 47 48
	return
}

// Save stores the current configuration object from memory.
ElyKar's avatar
ElyKar committed
49 50
func Save() {
	c := Config{viper.GetString("email"), viper.GetString("platform")}
51 52 53 54 55
	data, err := json.MarshalIndent(c, "", "  ")
	if err != nil {
		return
	}

ElyKar's avatar
ElyKar committed
56
	_ = ioutil.WriteFile(viper.GetString("file_config"), data, 0600)
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
}

// GetHomeDir is a helper to get the .dfss store directory
func GetHomeDir() string {
	u, err := user.Current()
	if err != nil {
		return ""
	}

	dfssPath := filepath.Join(u.HomeDir, ".dfss")
	if err := os.MkdirAll(dfssPath, os.ModeDir|0700); err != nil {
		return ""
	}

	return dfssPath + string(filepath.Separator)
}

func isFileValid(file string) bool {
	_, err := os.Stat(file)
	return err == nil
}