package config import ( "errors" "os" "path/filepath" "strings" ) // EnvFileName is the env file beside config.toml that setup writes secrets // to and the systemd units load with EnvironmentFile=-.../env. A process // started outside systemd -- a login shell running `archied update install` // -- does not have those variables, so anything that needs one loads the // file itself. const EnvFileName = "env" // EnvFilePath returns the env file beside the given config file, the same // path the systemd units' EnvironmentFile names. func EnvFilePath(configPath string) string { return filepath.Join(filepath.Dir(configPath), EnvFileName) } // defaultInstance mirrors configuration.DefaultInstance: the instance name // when ARCHIE_INSTANCE is unset. const defaultInstance = "archie" // DefaultConfigPath returns the config file archie binaries read when // -config is not given: $XDG_CONFIG_HOME//config.toml, or // ~/.config//config.toml. It mirrors configuration.DefaultConfigPath // so a process outside the configuration loader can still find the env file // beside that config. func DefaultConfigPath() string { dir := os.Getenv("XDG_CONFIG_HOME") if dir == "" { if home, err := os.UserHomeDir(); err == nil { dir = filepath.Join(home, ".config") } } instance := os.Getenv("ARCHIE_INSTANCE") if instance == "" { instance = defaultInstance } return filepath.Join(dir, instance, "config.toml") } // LoadEnvFile reads the env file at path. A missing file yields no entries // and no error: an install whose database_url carries its own password has // no env file to read. func LoadEnvFile(path string) (map[string]string, error) { data, err := os.ReadFile(path) if errors.Is(err, os.ErrNotExist) { return nil, nil } if err != nil { return nil, err } return ParseEnvFile(data), nil } // ParseEnvFile parses the env file format setup writes and systemd loads: // KEY='value' lines where a literal quote is escaped as '\” , plus unquoted // KEY=value and double-quoted KEY="value" lines. Blank lines and #-comments // are skipped, as are lines without a key. func ParseEnvFile(data []byte) map[string]string { entries := map[string]string{} for line := range strings.Lines(string(data)) { line = strings.TrimRight(line, "\r\n") trimmed := strings.TrimSpace(line) if trimmed == "" || strings.HasPrefix(trimmed, "#") { continue } key, value, ok := strings.Cut(trimmed, "=") if !ok || key == "" { continue } entries[key] = parseEnvValue(value) } return entries } // parseEnvValue strips the quoting one env-file value carries. The // single-quoted form is the one setup writes, so its '\” escape is undone. func parseEnvValue(value string) string { if len(value) >= 2 && value[0] == '\'' && value[len(value)-1] == '\'' { return strings.ReplaceAll(value[1:len(value)-1], `'\''`, "'") } if len(value) >= 2 && value[0] == '"' && value[len(value)-1] == '"' { return value[1 : len(value)-1] } return value }