// stats.go: a summary of the NAS in one screen: CPU, temperatures, memory, data volumes and network ports.
// With -json it prints the same facts as JSON, for a script or another program.
// Build and run it: go build stats.go && ./stats [-json]   (PROC and DF may point it at sample files)
package main

import (
	"cmp"
	"encoding/json"
	"flag"
	"fmt"
	"os"
	"os/exec"
	"strconv"
	"strings"
)

// The facts, as structs; the json tags name the fields of the JSON form.
type CPU struct {
	Name    string    `json:"name"`
	Cores   int       `json:"cores"`
	Logical int       `json:"logical_processors"`
	Load    []float64 `json:"load"`                    // the averages of 1, 5 and 15 minutes
	TempC   int       `json:"temperature_c,omitempty"` // omitempty: left out when getsysinfo is missing
}

type Volume struct {
	Name    string `json:"name"`
	SizeKiB int64  `json:"size_kib"`
	UsedKiB int64  `json:"used_kib"`
	UsedPct int    `json:"used_percent"`
}

type Port struct {
	Name    string `json:"name"`
	RxBytes int64  `json:"received_bytes"`
	TxBytes int64  `json:"sent_bytes"`
}

type Summary struct {
	Model     string   `json:"model,omitempty"`
	UptimeS   int      `json:"uptime_seconds"`
	CPU       CPU      `json:"cpu"`
	MemoryKiB int64    `json:"memory_kib"`
	AvailKiB  int64    `json:"memory_available_kib"`
	Volumes   []Volume `json:"volumes"`
	Ports     []Port   `json:"ports"`
}

func read(name string) string {
	b, _ := os.ReadFile(cmp.Or(os.Getenv("PROC"), "/proc") + "/" + name)
	return string(b)
}

func num(s string) int64 { n, _ := strconv.ParseInt(strings.TrimSuffix(s, "%"), 10, 64); return n }
func collect() Summary {
	var s Summary
	model, _ := exec.Command("getsysinfo", "model").Output()
	s.Model = strings.TrimSpace(string(model))
	fmt.Sscanf(read("uptime"), "%d", &s.UptimeS)
	cores, physical := map[string]bool{}, ""
	for _, l := range strings.Split(read("cpuinfo"), "\n") {
		k, v, _ := strings.Cut(l, ":")
		k, v = strings.TrimSpace(k), strings.TrimSpace(v)
		switch {
		case k == "processor":
			s.CPU.Logical++
		case k == "model name" && s.CPU.Name == "":
			s.CPU.Name = strings.NewReplacer("(R)", "", "(TM)", "", " CPU", "").Replace(v)
		case k == "physical id":
			physical = v
		case k == "core id":
			cores[physical+"-"+v] = true
		}
	}
	s.CPU.Cores = len(cores)
	for _, f := range strings.Fields(read("loadavg"))[:3] {
		x, _ := strconv.ParseFloat(f, 64)
		s.CPU.Load = append(s.CPU.Load, x)
	}
	if t, err := exec.Command("getsysinfo", "cputmp").Output(); err == nil {
		fmt.Sscanf(string(t), "%d", &s.CPU.TempC) // "53 C/127 F"
	}
	for _, l := range strings.Split(read("meminfo"), "\n") {
		if f := strings.Fields(l); len(f) > 1 && f[0] == "MemTotal:" {
			s.MemoryKiB = num(f[1])
		} else if len(f) > 1 && f[0] == "MemAvailable:" {
			s.AvailKiB = num(f[1])
		}
	}
	out, err := os.ReadFile(os.Getenv("DF"))
	if err != nil {
		out, _ = exec.Command("df", "-k").Output()
	}
	for _, l := range strings.Split(string(out), "\n") {
		if f := strings.Fields(l); len(f) > 5 && strings.HasPrefix(f[5], "/share/") && strings.Count(f[5], "/") == 2 {
			s.Volumes = append(s.Volumes, Volume{strings.TrimPrefix(f[5], "/share/"), num(f[1]), num(f[2]), int(num(f[4]))})
		}
	}
	for _, l := range strings.Split(read("net/dev"), "\n") {
		name, rest, ok := strings.Cut(l, ":")
		if f := strings.Fields(rest); ok && strings.HasPrefix(strings.TrimSpace(name), "eth") && len(f) > 8 {
			s.Ports = append(s.Ports, Port{strings.TrimSpace(name), num(f[0]), num(f[8])})
		}
	}
	return s
}

const amber, green, red, dim, bold, reset = "\033[38;5;214m", "\033[32m", "\033[31m", "\033[2m", "\033[1m", "\033[0m"

// bar fills pct percent of width: green up to 69 %, amber up to 89 %, red from 90 %.
func bar(pct, width int) string {
	c := green
	if pct >= 70 {
		c = amber
	}
	if pct >= 90 {
		c = red
	}
	return c + strings.Repeat("█", pct*width/100) + dim + strings.Repeat("░", width-pct*width/100) + reset
}

func gib(kib int64) string { return fmt.Sprintf("%.1f GiB", float64(kib)/1048576) }
func head(title string) {
	fmt.Printf("\n %s%s%s %s%s\n", bold+amber, title, reset+amber, strings.Repeat("─", 76-len([]rune(title))), reset)
}

func main() {
	asJSON := flag.Bool("json", false, "print the facts as JSON")
	flag.Parse()
	s := collect()
	if *asJSON {
		e := json.NewEncoder(os.Stdout)
		e.SetIndent("", "  ")
		e.Encode(s)
		return
	}
	fmt.Printf("%s %-40s%39s%s\n", "\033[1;30;48;5;214m", "NAS summary", s.Model, reset)
	head("CPU")
	fmt.Printf("  %s%s%s, %d cores, %d logical processors\n", bold, s.CPU.Name, reset, s.CPU.Cores, s.CPU.Logical)
	pct := int(s.CPU.Load[0] * 100 / float64(s.CPU.Logical))
	fmt.Printf("  Load %.2f %.2f %.2f   %s %d %% of the logical processors\n", s.CPU.Load[0], s.CPU.Load[1], s.CPU.Load[2], bar(pct, 20), pct)
	fmt.Printf("  Up for %d d %d h %d min", s.UptimeS/86400, s.UptimeS%86400/3600, s.UptimeS%3600/60)
	if s.CPU.TempC > 0 {
		fmt.Printf("   temperature %s%d °C%s", green, s.CPU.TempC, reset)
	}
	fmt.Println()
	head("Memory")
	used := s.MemoryKiB - s.AvailKiB
	fmt.Printf("  %s %3d %%   %s of %s in use, %s%s%s available\n", bar(int(used*100/s.MemoryKiB), 20),
		used*100/s.MemoryKiB, gib(used), gib(s.MemoryKiB), green, gib(s.AvailKiB), reset)
	head("Volumes")
	for _, v := range s.Volumes {
		fmt.Printf("  %-16s%s %3d %%   %s of %s\n", v.Name, bar(v.UsedPct, 30), v.UsedPct, gib(v.UsedKiB), gib(v.SizeKiB))
	}
	head("Network ports")
	for _, p := range s.Ports {
		fmt.Printf("  %-6s received %10s   sent %10s\n", p.Name, gib(p.RxBytes/1024), gib(p.TxBytes/1024))
	}
}
