// menu.go: a framed menu in Go with raw keys. The arrow keys move the bar, Enter opens a box with the NAS's memory,
// volumes or uptime and load, any key closes it, q quits. Run: go build menu.go && ./menu (PROC, DF: sample files)
package main

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

const amber, green, red, dim, bold, reset = "\033[38;5;214m", "\033[32m", "\033[31m", "\033[2m", "\033[1m", "\033[0m"
const barColour = "\033[1;30;48;5;214m"       // black letters on amber
var proc = cmp.Or(os.Getenv("PROC"), "/proc") // the root of /proc; the test points it at a sample

func at(line, col int, format string, a ...any) {
	fmt.Printf("\033[%d;%dH"+format, append([]any{line, col}, a...)...)
}

// box draws a double frame in amber with its title in the top edge.
func box(line, col, height, width int, title string) {
	at(line, col, "%s╔%s╗", amber, strings.Repeat("═", width-2))
	for i := 1; i < height-1; i++ {
		at(line+i, col, "║%s║", strings.Repeat(" ", width-2))
	}
	at(line+height-1, col, "╚%s╝", strings.Repeat("═", width-2))
	at(line, col+2, "%s %s %s", bold+amber, title, reset)
}

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

func gib(kib int64) string        { return fmt.Sprintf("%.1f GiB", float64(kib)/1048576) }
func readFile(name string) string { b, _ := os.ReadFile(proc + "/" + name); return string(b) }

func showMemory() {
	m := map[string]int64{}
	for _, l := range strings.Split(readFile("meminfo"), "\n") {
		if f := strings.Fields(l); len(f) >= 2 {
			m[strings.TrimSuffix(f[0], ":")], _ = strconv.ParseInt(f[1], 10, 64)
		}
	}
	used := m["MemTotal"] - m["MemAvailable"]
	pct := int(used * 100 / m["MemTotal"])
	box(6, 32, 7, 46, "Memory")
	at(8, 35, "Total      %s", gib(m["MemTotal"]))
	at(9, 35, "In use     %s", gib(used))
	at(10, 35, "Available  %s%s%s", green, gib(m["MemAvailable"]), reset)
	at(11, 35, "%s %d %%", bar(pct, 30), pct)
}

func showVolumes() {
	out, err := os.ReadFile(os.Getenv("DF")) // a sample of df -k, or else the real one
	if err != nil {
		out, _ = exec.Command("df", "-k").Output()
	}
	box(6, 32, 8, 46, "Volumes")
	line := 8
	for _, l := range strings.Split(string(out), "\n") {
		f := strings.Fields(l)
		if len(f) < 6 || !strings.HasPrefix(f[5], "/share/") || strings.Count(f[5], "/") != 2 {
			continue // only the data volumes, one level under /share
		}
		size, _ := strconv.ParseInt(f[1], 10, 64)
		used, _ := strconv.ParseInt(f[2], 10, 64)
		pct, _ := strconv.Atoi(strings.TrimSuffix(f[4], "%"))
		at(line, 35, "%s%-15s%s %s of %s", bold, strings.TrimPrefix(f[5], "/share/"), reset, gib(used), gib(size))
		at(line+1, 35, "%s %d%%", bar(pct, 30), pct)
		line += 2
	}
}

func showUptime() {
	var s int
	fmt.Sscanf(readFile("uptime"), "%d", &s) // the whole seconds before the dot
	load := strings.Fields(readFile("loadavg"))
	logical, physical, cores := 0, "", map[string]bool{}
	for _, l := range strings.Split(readFile("cpuinfo"), "\n") {
		k, v, _ := strings.Cut(l, ":")
		switch strings.TrimSpace(k) {
		case "processor":
			logical++
		case "physical id":
			physical = strings.TrimSpace(v)
		case "core id":
			cores[physical+"-"+strings.TrimSpace(v)] = true // a core is a distinct pair of physical id and core id
		}
	}
	box(6, 32, 9, 46, "Uptime and load")
	at(8, 35, "Up for     %s%d d %d h %d min%s", bold, s/86400, s%86400/3600, s%3600/60, reset)
	at(9, 35, "Load       %s / %s / %s", load[0], load[1], load[2])
	at(10, 35, "%s           1, 5 and 15 minutes%s", dim, reset)
	at(11, 35, "Cores      %d", len(cores))
	at(12, 35, "Processors %d logical", logical)
}

var items = []string{"Memory", "Volumes", "Uptime and load"}

func draw(sel int) {
	model, _ := exec.Command("getsysinfo", "model").Output() // QNAP's own command; on a PC the title stays short
	at(1, 1, "\033[2J%s %-58s%21s%s", barColour, "NAS menu", strings.TrimSpace(string(model)), reset)
	box(4, 4, len(items)+4, 24, "Menu")
	for i, it := range items {
		if i == sel {
			at(6+i, 6, "%s ▶ %-17s%s", barColour, it, reset)
		} else {
			at(6+i, 6, "   %-17s", it)
		}
	}
	at(24, 1, "%s ↑↓ move   Enter open   q quit%s", dim, reset)
}

// key reads one key press; an arrow key arrives as three bytes in one read.
func key() string {
	b := make([]byte, 8)
	if n, err := os.Stdin.Read(b); err == nil {
		return string(b[:n])
	}
	return "q"
}

func main() {
	stty := func(args ...string) string { // stty works on the terminal it gets as its input
		c := exec.Command("stty", args...)
		c.Stdin = os.Stdin
		out, _ := c.Output()
		return strings.TrimSpace(string(out))
	}
	saved := stty("-g") // the terminal's settings, to put back at the end
	stty("raw", "-echo")
	fmt.Print("\033[?1049h\033[?25l") // a screen of its own, no cursor
	defer func() { fmt.Print("\033[0m\033[?25h\033[?1049l"); stty(saved) }()

	for sel := 0; ; {
		draw(sel)
		switch key() {
		case "\033[A", "\033OA":
			sel = (sel + len(items) - 1) % len(items)
		case "\033[B", "\033OB":
			sel = (sel + 1) % len(items)
		case "q", "Q", "\003": // \003 is Ctrl+C, which raw mode delivers as a byte
			return
		case "\r":
			[]func(){showMemory, showVolumes, showUptime}[sel]()
			at(24, 1, "\033[2K%s Any key closes the box%s", dim, reset)
			key()
		}
	}
}
