aboutsummaryrefslogtreecommitdiffhomepage
path: root/internal/state/print.go
blob: 6610ada24286745e49c02eedf778e3035bb48a9b (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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package state

import (
	"flag"
	"fmt"
	"os"
	"strconv"
	"strings"
	"text/tabwriter"

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

var (
	stateActionEarly  bool
	stateActionEarlyC bool
)

func init() {
	flag.BoolVar(&stateActionEarly, "state", false, "print state information of active launchers")
	flag.BoolVar(&stateActionEarlyC, "state-current", false, "print state information of active launchers for the specified user")
}

func Early() {
	var w *tabwriter.Writer

	switch {
	case stateActionEarly:
		if runDir, err := os.ReadDir(system.V.RunDir); err != nil {
			fmt.Println("Error reading runtime directory:", err)
		} else {
			for _, e := range runDir {
				if !e.IsDir() {
					if system.V.Verbose {
						fmt.Println("Skipped non-directory entry", e.Name())
					}
					continue
				}

				if _, err = strconv.Atoi(e.Name()); err != nil {
					if system.V.Verbose {
						fmt.Println("Skipped non-uid entry", e.Name())
					}
					continue
				}

				printLauncherState(e.Name(), &w)
			}
		}
	case stateActionEarlyC:
		printLauncherState(u.Uid, &w)
	default:
		return
	}

	if w != nil {
		if err := w.Flush(); err != nil {
			fmt.Println("warn: error formatting output:", err)
		}
	} else {
		fmt.Println("No information available.")
	}

	os.Exit(0)
}

func printLauncherState(uid string, w **tabwriter.Writer) {
	launchers, err := readLaunchers(uid)
	if err != nil {
		fmt.Println("Error reading launchers:", err)
		os.Exit(1)
	}

	if *w == nil {
		*w = tabwriter.NewWriter(os.Stdout, 0, 1, 4, ' ', 0)

		if !system.V.Verbose {
			_, _ = fmt.Fprintln(*w, "\tUID\tPID\tEnablements\tLauncher\tCommand")
		} else {
			_, _ = fmt.Fprintln(*w, "\tUID\tPID\tArgv")
		}
	}

	for _, state := range launchers {
		enablementsDescription := strings.Builder{}
		for i := Enablement(0); i < enableLength; i++ {
			if state.Capability.Has(i) {
				enablementsDescription.WriteString(", " + i.String())
			}
		}
		if enablementsDescription.Len() == 0 {
			enablementsDescription.WriteString("none")
		}

		if !system.V.Verbose {
			_, _ = fmt.Fprintf(*w, "\t%s\t%d\t%s\t%s\t%s\n",
				uid, state.PID, strings.TrimPrefix(enablementsDescription.String(), ", "), state.Launcher,
				state.Command)
		} else {
			_, _ = fmt.Fprintf(*w, "\t%s\t%d\t%s\n",
				uid, state.PID, state.Argv)
		}
	}
}