package main

// The last lines a failed unit logged, for its explanation on the account page. Read from the
// tail of the classic syslog file (/var/log/syslog on Debian and Ubuntu, /var/log/messages on
// RHEL), which rsyslog fills from the journal; the agent never runs journalctl (it executes no
// commands at all). Systems that log only to journald send none. Only done once per unit when it
// newly fails, at most unitLogRead bytes; each line is redacted like a command line and cut to 300
// characters.

import (
	"bytes"
	"os"
	"path/filepath"
	"strings"
)

const unitLogRead = 1 << 20

// SyslogPath: the first syslog file that exists.
func SyslogPath(root string) string {
	for _, p := range []string{"var/log/syslog", "var/log/messages"} {
		if fi, err := os.Stat(filepath.Join(root, p)); err == nil && fi.Mode().IsRegular() {
			return filepath.Join(root, p)
		}
	}
	return ""
}

// UnitLogTails returns the last (at most 10) lines about each unit in the syslog file's tail:
// lines naming the unit ("cloud-init.service: Main process exited…") or written by its program
// ("cloud-init[612]: …").
func UnitLogTails(path string, units []string) (map[string][]string, error) {
	out := map[string][]string{}
	if path == "" || len(units) == 0 {
		return out, nil
	}
	f, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()
	fi, err := f.Stat()
	if err != nil {
		return nil, err
	}
	from := max(0, fi.Size()-unitLogRead)
	buf := make([]byte, fi.Size()-from)
	n, _ := f.ReadAt(buf, from)
	buf = buf[:n]
	if from > 0 {
		if i := bytes.IndexByte(buf, '\n'); i >= 0 {
			buf = buf[i+1:]
		}
	}
	type pat struct{ unit, ident []byte }
	pats := make([]pat, 0, len(units))
	for _, u := range units {
		base := u
		if i := strings.LastIndexByte(u, '.'); i > 0 {
			base = u[:i]
		}
		ident := []byte(" " + base + "[")
		if strings.Contains(base, "@") { // user@1000: its own lines come from "systemd[pid]"
			ident = nil
		}
		pats = append(pats, pat{unit: []byte(u), ident: ident})
	}
	lines := bytes.Split(buf, []byte("\n"))
	for i := len(lines) - 1; i >= 0; i-- {
		l := lines[i]
		for k, p := range pats {
			u := units[k]
			if len(out[u]) >= 10 {
				continue
			}
			if bytes.Contains(l, p.unit) || (p.ident != nil && bytes.Contains(l, p.ident)) {
				out[u] = append(out[u], truncate(Redact(stripSyslogPrefix(string(l))), 300))
			}
		}
	}
	for u, ls := range out { // oldest first
		for i, j := 0, len(ls)-1; i < j; i, j = i+1, j-1 {
			ls[i], ls[j] = ls[j], ls[i]
		}
		out[u] = ls
	}
	return out, nil
}

// stripSyslogPrefix drops the time and host name: "2026-10-07T10:00:00+00:00 host prog[1]: msg" or
// "Oct  7 10:00:00 host prog[1]: msg" become "prog[1]: msg".
func stripSyslogPrefix(l string) string {
	f := strings.Fields(l)
	skip := 2 // RFC 3339 time, host
	if len(f) > 0 && len(f[0]) == 3 && !strings.ContainsAny(f[0], "0123456789") {
		skip = 4 // month day time host
	}
	if len(f) <= skip {
		return strings.TrimSpace(l)
	}
	return strings.Join(f[skip:], " ")
}
