// hello.go: a greeting for the SSH login. A text/template lays out the facts of the NAS: a greeting for the time of
// day, the model, uptime, CPU, load, the free space of the data volumes and a tip of the day; the code frames it.
// Build and run it: go build hello.go && ./hello   (NOW, SEED, PROC and DF may replace the clock and the files)
package main

import (
	"bytes"
	"cmp"
	"fmt"
	"os"
	"os/exec"
	"os/user"
	"strconv"
	"strings"
	"text/template"
	"time"
)

const width = 76 // the frame's width

// The template holds only the content; {{col 57}} jumps to column 57, the functions add the colours.
const banner = `{{amber "░▒▓█"}} {{bold (printf "%s, %s" .Greeting .User)}} {{amber "█▓▒░"}}{{col 57}}{{dim .Date}}

{{printf "%-12s" "Model"}}{{bold .Model}}
{{printf "%-12s" "Up for"}}{{.Uptime}}
{{printf "%-12s" "CPU"}}{{.Cores}} cores, {{.Logical}} logical processors
{{printf "%-12s" "Load"}}{{index .Load 0}}  {{index .Load 1}}  {{index .Load 2}}  {{dim "(1, 5 and 15 minutes)"}}

{{bold "Free space on the data volumes"}}
{{range .Volumes}}{{printf "%-16s" .Name}}{{bar .Pct}}  {{green (gib .Free)}} free of {{gib .Size}}
{{end}}
{{amber "Tip"}}  {{.Tip}}`

type volume struct {
	Name       string
	Size, Free int64 // KiB
	Pct        int
}

type facts struct {
	Greeting, User, Date, Model, Uptime, Tip string
	Cores, Logical                           int
	Load                                     []string
	Volumes                                  []volume
}

var tips = []string{
	"getsysinfo cputmp prints the temperature of the CPU.",
	"cat /proc/mdstat shows the state of every RAID group.",
	"getcfg System Version prints the version of QTS.",
	"ls /share lists the shared folders of the NAS.",
	"df -h shows the size and the free space of every volume.",
	"uptime prints how long the NAS has run and its load.",
}

func colour(code string) func(string) string {
	return func(s string) string { return "\033[" + code + "m" + s + "\033[0m" }
}

var funcs = template.FuncMap{
	"amber": colour("38;5;214"), "green": colour("32"), "bold": colour("1"), "dim": colour("2"),
	"col": func(n int) string { return fmt.Sprintf("\033[%dG", n) },
	"gib": func(kib int64) string { return fmt.Sprintf("%.1f GiB", float64(kib)/1048576) },
	"bar": func(pct int) string { // 20 cells: green up to 69 %, amber up to 89 %, red from 90 %
		c := "32"
		if pct >= 70 {
			c = "38;5;214"
		}
		if pct >= 90 {
			c = "31"
		}
		return colour(c)(strings.Repeat("█", pct/5)) + colour("2")(strings.Repeat("░", 20-pct/5))
	},
}

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

func gather() facts {
	now, err := time.ParseInLocation(time.DateTime, os.Getenv("NOW"), time.Local)
	if err != nil {
		now = time.Now()
	}
	f := facts{Date: now.Format("2006-01-02 15:04"), Load: strings.Fields(read("loadavg"))[:3]}
	switch h := now.Hour(); {
	case h >= 5 && h < 12:
		f.Greeting = "Good morning"
	case h >= 12 && h < 18:
		f.Greeting = "Good afternoon"
	case h >= 18 && h < 22:
		f.Greeting = "Good evening"
	default:
		f.Greeting = "Working late"
	}
	seed, err := strconv.Atoi(os.Getenv("SEED"))
	if err != nil {
		seed = now.YearDay() // without SEED, a new tip each day
	}
	f.Tip = tips[seed%len(tips)]
	f.User = os.Getenv("USER")
	if u, err := user.Current(); f.User == "" && err == nil {
		f.User = u.Username
	}
	model, _ := exec.Command("getsysinfo", "model").Output()
	f.Model = strings.TrimSpace(string(model))
	var s int
	fmt.Sscanf(read("uptime"), "%d", &s)
	f.Uptime = fmt.Sprintf("%d d %d h %d min", s/86400, s%86400/3600, s%3600/60)
	cores, physical := map[string]bool{}, ""
	for _, l := range strings.Split(read("cpuinfo"), "\n") {
		k, v, _ := strings.Cut(l, ":")
		switch strings.TrimSpace(k) {
		case "processor":
			f.Logical++
		case "physical id":
			physical = strings.TrimSpace(v)
		case "core id":
			cores[physical+"-"+strings.TrimSpace(v)] = true
		}
	}
	f.Cores = len(cores)
	out, err := os.ReadFile(os.Getenv("DF"))
	if err != nil {
		out, _ = exec.Command("df", "-k").Output()
	}
	for _, l := range strings.Split(string(out), "\n") {
		w := strings.Fields(l)
		if len(w) < 6 || !strings.HasPrefix(w[5], "/share/") || strings.Count(w[5], "/") != 2 {
			continue // only the data volumes, one level under /share
		}
		v := volume{Name: strings.TrimPrefix(w[5], "/share/")}
		v.Size, _ = strconv.ParseInt(w[1], 10, 64)
		v.Free, _ = strconv.ParseInt(w[3], 10, 64)
		v.Pct, _ = strconv.Atoi(strings.TrimSuffix(w[4], "%"))
		f.Volumes = append(f.Volumes, v)
	}
	return f
}

func main() {
	var body bytes.Buffer
	t := template.Must(template.New("banner").Funcs(funcs).Parse(banner))
	if err := t.Execute(&body, gather()); err != nil {
		fmt.Fprintln(os.Stderr, "hello:", err)
		os.Exit(1)
	}
	a, n := "\033[38;5;214m", "\033[0m" // amber frame, then back to normal
	fmt.Printf("%s╔═ Hello %s╗%s\n", a, strings.Repeat("═", width-10), n)
	fmt.Printf("%s║%s\033[%dG%s║%s\n", a, n, width, a, n)
	for _, line := range strings.Split(body.String(), "\n") {
		fmt.Printf("%s║%s   %s\033[%dG%s║%s\n", a, n, line, width, a, n)
	}
	fmt.Printf("%s║%s\033[%dG%s║%s\n%s╚%s╝%s\n", a, n, width, a, n, a, strings.Repeat("═", width-2), n)
}
