aboutsummaryrefslogtreecommitdiffhomepage
path: root/util.go
blob: 2de8f3be44c554c513ccf5c28aedccec106e7460 (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
package main

import (
	"errors"
	"fmt"
	"io"
	"io/fs"
	"os"
	"os/exec"
)

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

// https://www.freedesktop.org/software/systemd/man/sd_booted.html
func sdBooted() bool {
	_, err := os.Stat(systemdCheckPath)
	if err != nil {
		if 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
}

func which(file string) (string, bool) {
	path, err := exec.LookPath(file)
	return path, err == nil
}

func copyFile(dst, src string) error {
	srcD, err := os.Open(src)
	if err != nil {
		return err
	}
	defer func() {
		if srcD.Close() != nil {
			// unreachable
			panic("src file closed prematurely")
		}
	}()

	dstD, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		return err
	}
	defer func() {
		if dstD.Close() != nil {
			// unreachable
			panic("dst file closed prematurely")
		}
	}()

	_, err = io.Copy(dstD, srcD)
	return err
}