package system

import (
	"os"
	"strings"

	"nadir/internal/oscmd"
)

type OSInfo struct {
	PrettyName   string `json:"pretty_name" example:"Fedora Linux 44 (Workstation Edition)" doc:"Distro name from /etc/os-release PRETTY_NAME"`
	Kernel       string `json:"kernel" example:"7.0.12-201.fc44.x86_64" doc:"Running kernel release (uname -r)"`
	Architecture string `json:"architecture" example:"x86_64" doc:"Machine hardware architecture (uname -m)"`
	Hostname     string `json:"hostname" example:"server01" doc:"System hostname"`
}

func osInfo() OSInfo {
	host, _ := os.Hostname()
	return OSInfo{
		PrettyName:   osReleasePretty(),
		Kernel:       firstLine(oscmd.Run("uname", "-r")),
		Architecture: firstLine(oscmd.Run("uname", "-m")),
		Hostname:     host,
	}
}

// firstLine discards a command error and returns its (already trimmed) output,
// used where a missing value is acceptable.
func firstLine(out string, _ error) string { return out }

func osReleasePretty() string {
	data, err := os.ReadFile("/etc/os-release")
	if err != nil {
		return ""
	}
	for line := range strings.SplitSeq(string(data), "\n") {
		if v, ok := strings.CutPrefix(line, "PRETTY_NAME="); ok {
			return strings.Trim(v, `"`)
		}
	}
	return ""
}
