aboutsummaryrefslogtreecommitdiff
path: root/src/config.go
blob: 8f931aeb98cd08f29065aaf3aeaad878c4ae9e3f (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
package src

import (
	"fmt"
	"os"
	"path/filepath"
	"runtime"

	"github.com/BurntSushi/toml"
)

type Config struct {
	path string

	BaseURL  string
	Username string
	Password string
}

func LoadConfigFromFile(filename string) (*Config, error) {
	var cfg Config
	_, err := toml.DecodeFile(filename, &cfg)

	cfg.path = filename

	return &cfg, err
}

func LoadDefaultConfig() (*Config, error) {
	path, err := getConfigFilePath()
	if err != nil {
		return nil, err
	}

	f, err := os.Open(path)
	if err != nil && !os.IsNotExist(err) {
		return nil, err
	} else if os.IsNotExist(err) {
		return &Config{path: path}, nil
	}
	f.Close()

	return LoadConfigFromFile(path)
}

func getConfigFilePath() (string, error) {
	path := ""
	if runtime.GOOS == "linux" || runtime.GOOS == "openbsd" {
		configDir := os.Getenv("XDG_CONFIG_DIR")
		if configDir == "" {
			home := os.Getenv("HOME")
			if home == "" {
				return "", fmt.Errorf("could not determine where to store configuration")
			}

			path = filepath.Join(home, ".config")
			os.MkdirAll(path, os.ModeDir.Perm())

			path = filepath.Join(path, "termsonic.toml")
		} else {
			path = filepath.Join(configDir, "termsonic.toml")
		}
	} else if runtime.GOOS == "windows" {
		appdata := os.Getenv("APPDATA")
		if appdata == "" {
			return "", fmt.Errorf("could not find %%APPDATA%%")
		}

		path = filepath.Join(appdata, "Termsonic")
		os.MkdirAll(path, os.ModeDir.Perm())

		path = filepath.Join(path, "termsonic.toml")
	} else {
		return "", fmt.Errorf("unsupported operating system: %s", runtime.GOOS)
	}

	return path, nil
}

func (c *Config) Save() error {
	f, err := os.Create(c.path)
	if err != nil {
		return err
	}
	defer f.Close()

	enc := toml.NewEncoder(f)
	return enc.Encode(*c)
}