aboutsummaryrefslogtreecommitdiffhomepage
path: root/internal/util/std.go
blob: 5c37a0d7bb6b86702174e801efb03a5c96f0caa7 (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
package util

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
	"path"

	"git.ophivana.moe/cat/fortify/internal/state"
	"git.ophivana.moe/cat/fortify/internal/system"
)

const (
	systemdCheckPath = "/run/systemd/system"

	home          = "HOME"
	xdgConfigHome = "XDG_CONFIG_HOME"

	PulseServer = "PULSE_SERVER"
	PulseCookie = "PULSE_COOKIE"
)

// SdBooted implements https://www.freedesktop.org/software/systemd/man/sd_booted.html
func SdBooted() bool {
	_, err := os.Stat(systemdCheckPath)
	if err != nil {
		if system.V.Verbose {
			if errors.Is(err, fs.ErrNotExist) {
				fmt.Println("System not booted through systemd")
			} else {
				fmt.Println("Error accessing", systemdCheckPath+":", err.Error())
			}
		}
		return false
	}
	return true
}

// DiscoverPulseCookie try various standard methods to discover the current user's PulseAudio authentication cookie
func DiscoverPulseCookie() string {
	if p, ok := os.LookupEnv(PulseCookie); ok {
		return p
	}

	if p, ok := os.LookupEnv(home); ok {
		p = path.Join(p, ".pulse-cookie")
		if s, err := os.Stat(p); err != nil {
			if !errors.Is(err, fs.ErrNotExist) {
				state.Fatal("Error accessing PulseAudio cookie:", err)
				// unreachable
				return p
			}
		} else if !s.IsDir() {
			return p
		}
	}

	if p, ok := os.LookupEnv(xdgConfigHome); ok {
		p = path.Join(p, "pulse", "cookie")
		if s, err := os.Stat(p); err != nil {
			if !errors.Is(err, fs.ErrNotExist) {
				state.Fatal("Error accessing PulseAudio cookie:", err)
				// unreachable
				return p
			}
		} else if !s.IsDir() {
			return p
		}
	}

	state.Fatal(fmt.Sprintf("Cannot locate PulseAudio cookie (tried $%s, $%s/pulse/cookie, $%s/.pulse-cookie)",
		PulseCookie, xdgConfigHome, home))
	return ""
}