about summary refs log tree commit diff stats
path: root/uptime.go
blob: 07bcc4703cb15a122f12c8786739f21311f2376f (plain) (blame)
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
package main

import (
	"fmt"
	"os/exec"
	"strings"
)

// executes uptime and responds with a []byte{}
// TODO: account for uptimes <1d and >1d
func uptimeQuery(format string) ([]byte, error) {
	out, err := exec.Command("/usr/bin/uptime").Output()
	if err != nil {
		return nil, fmt.Errorf("Could not execute /usr/bin/uptime: %w", err)
	}

	split := strings.Split(string(out), ",")

	if format == "plain" {
		cut := fmt.Sprintf("%s,%s,%s,%s", split[0], split[1], split[3], split[4])
		return []byte(cut), nil
	}

	timeup := strings.Split(string(split[0]), " ")
	time := timeup[0]
	up := fmt.Sprintf("%s,%s", timeup[1:], split[1])

	loadcomb := strings.Split(string(split[3]), " ")
	loads := fmt.Sprintf("%s,%s,%s", loadcomb[1], split[3], split[4])

	json := fmt.Sprintf(`{
	"time": "%s",
	"up": "%s",
	"load": "%s"
}
`, time, up, loads)

	return []byte(json), nil
}