aboutsummaryrefslogtreecommitdiffhomepage
path: root/internal/app/env.go
blob: 4305c665128e2b74e4ebfe3c94f3bf9d955b2520 (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
package app

import (
	"strconv"

	"hakurei.app/container"
	"hakurei.app/hst"
)

// EnvPaths holds paths copied from the environment and is used to create [hst.Paths].
type EnvPaths struct {
	// TempDir is returned by [os.TempDir].
	TempDir *container.Absolute
	// RuntimePath is copied from $XDG_RUNTIME_DIR.
	RuntimePath *container.Absolute
}

// Copy expands [EnvPaths] into [hst.Paths].
func (env *EnvPaths) Copy(v *hst.Paths, userid int) {
	if env == nil || env.TempDir == nil || v == nil {
		panic("attempting to use an invalid EnvPaths")
	}

	v.TempDir = env.TempDir
	v.SharePath = env.TempDir.Append("hakurei." + strconv.Itoa(userid))

	if env.RuntimePath == nil {
		// fall back to path in share since hakurei has no hard XDG dependency
		v.RunDirPath = v.SharePath.Append("run")
		v.RuntimePath = v.RunDirPath.Append("compat")
	} else {
		v.RuntimePath = env.RuntimePath
		v.RunDirPath = env.RuntimePath.Append("hakurei")
	}
}

// CopyPaths returns a populated [EnvPaths].
func CopyPaths() *EnvPaths { return copyPaths(direct{}) }

// copyPaths returns a populated [EnvPaths].
func copyPaths(k syscallDispatcher) *EnvPaths {
	const xdgRuntimeDir = "XDG_RUNTIME_DIR"

	var env EnvPaths

	if tempDir, err := container.NewAbs(k.tempdir()); err != nil {
		k.fatalf("invalid TMPDIR: %v", err)
		panic("unreachable")
	} else {
		env.TempDir = tempDir
	}

	r, _ := k.lookupEnv(xdgRuntimeDir)
	if a, err := container.NewAbs(r); err == nil {
		env.RuntimePath = a
	}

	return &env
}