package main

// The 0.3.0 parts of the collector: login history, failed-unit details, port owners, disk usage
// scans and disk writers. All of it runs on the background worker (main.go), never on the sampling
// loop; what it finds waits under c.mu until the next rollup takes it.

import (
	"encoding/json"
	"log/slog"
	"os"
	"path/filepath"
	"sort"
	"time"
)

type loginState struct {
	Version string    `json:"version"`
	Wtmp    wtmpState `json:"wtmp"`
	Auth    *AuthPos  `json:"auth,omitempty"`
}

// LoginsOut is the rollup's login block (see the wire format in README.md).
type LoginsOut struct {
	Backfill bool             `json:"backfill,omitempty"`
	Wtmp     string           `json:"wtmp,omitempty"` // ok | unreadable | missing
	Auth     string           `json:"auth,omitempty"` // ok | unreadable | missing
	Recent   []LoginRec       `json:"recent,omitempty"`
	Boots    []BootRec        `json:"boots,omitempty"`
	Sessions []SessionRec     `json:"sessions"`
	Last     map[string]int64 `json:"last,omitempty"`
	Accepted []AcceptedRec    `json:"accepted,omitempty"`
	Failed   []FailedIP       `json:"failed,omitempty"`
	Sudo     []SudoRec        `json:"sudo,omitempty"`
}

// FailedIP: one source address's failed SSH attempts in the rollup window.
type FailedIP struct {
	IP      string   `json:"ip"`
	N       int      `json:"n"`
	Invalid int      `json:"invalid"`
	LastAt  int64    `json:"last_at,omitempty"`
	Users   []string `json:"users,omitempty"` // existing accounts only
}

type extra struct {
	persist bool

	// logins (guarded by c.mu)
	lg         loginState
	lgLoaded   bool
	wtmpErr    string
	recent     []LoginRec
	boots      []BootRec
	sessions   []SessionRec
	sessHash   string
	sessSent   string
	last       map[string]int64
	lastSent   string
	backfill   bool
	loginsSent bool // since this start
	lastlogMt  time.Time
	lastlog    map[string]int64
	authDirty  bool

	// failed units (c.mu)
	unitProps func(string, time.Duration, []UnitInfo) (map[string]UnitDetail, error)
	unitDet   map[string]UnitDetail
	unitDetAt time.Time
	unitKey   string
	logged    map[string]int64 // unit -> the failure (since) whose log lines were already sent
	syslogErr string

	// disk (c.mu)
	disk       *DiskScanner
	diskOut    *DiskScanOut
	writers    *WriteTracker
	writersOut []WriterOut

	// rollup ports (sampling goroutine)
	portsHash string
}

func (c *Collector) initExtra() {
	c.x.unitProps = UnitDetails
	c.x.unitDet = map[string]UnitDetail{}
	c.x.logged = map[string]int64{}
	c.x.disk = NewDiskScanner()
	c.x.writers = NewWriteTracker()
	c.x.last = map[string]int64{}
}

func (c *Collector) loginStatePath() string { return filepath.Join(c.cfg.StateDir, "logins.json") }

// LoadLoginState restores where the wtmp and auth log readers stopped (persist: the service; the
// `check` command and --dry-run neither read nor write it and backfill every time).
func (c *Collector) LoadLoginState(persist bool) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.x.persist = persist
	c.x.lgLoaded = true
	if persist {
		if b, err := readSmall(c.loginStatePath(), 4<<20); err == nil {
			var st loginState
			if json.Unmarshal(b, &st) == nil {
				c.x.lg = st
			}
		}
	}
	c.auth.Resume(c.x.lg.Auth)
	c.auth.Backfill = !c.auth.started
	c.x.backfill = c.x.lg.Wtmp.Ino == 0
}

func (c *Collector) saveLoginState() {
	if !c.x.persist {
		return
	}
	c.x.lg.Version = c.version
	c.x.lg.Auth = c.auth.Pos()
	if b, err := json.Marshal(c.x.lg); err == nil {
		if err := writeFileAtomic(c.loginStatePath(), b, 0o600); err != nil {
			logLimited("login-state", time.Hour, slog.LevelWarn, "cannot save the login reader state", "err", err)
		}
	}
}

// ReadLogins reads wtmp (new records), utmp (who is logged in) and lastlog (when it changed).
func (c *Collector) ReadLogins() {
	if !c.cfg.On("logins") {
		return
	}
	c.mu.Lock()
	if !c.x.lgLoaded {
		c.mu.Unlock()
		c.LoadLoginState(false)
		c.mu.Lock()
	}
	st := c.x.lg.Wtmp // a copy: the read happens without the lock
	if st.Open != nil {
		cp := make(map[string]LoginRec, len(st.Open))
		for k, v := range st.Open {
			cp[k] = v
		}
		st.Open = cp
	}
	if st.Last != nil {
		cp := make(map[string]int64, len(st.Last))
		for k, v := range st.Last {
			cp[k] = v
		}
		st.Last = cp
	}
	backfill := c.x.backfill
	c.mu.Unlock()

	ev, err := ReadWtmp(filepath.Join(c.host, "var/log/wtmp"), &st, backfill)
	wtmpErr := ""
	switch {
	case err == nil:
	case os.IsNotExist(err):
		wtmpErr = "missing"
	case os.IsPermission(err):
		wtmpErr = "unreadable"
	default:
		wtmpErr = "error"
		logLimited("wtmp", time.Hour, slog.LevelWarn, "cannot read wtmp", "err", err)
	}
	sessions, serr := ReadUtmpSessions(c.host, c.proc)
	if serr != nil {
		sessions = nil
	}
	var lastlog map[string]int64
	llPath := filepath.Join(c.host, "var/log/lastlog")
	fi, llErr := os.Stat(llPath)

	c.mu.Lock()
	defer c.mu.Unlock()
	if llErr == nil && !fi.ModTime().Equal(c.x.lastlogMt) {
		rs := 292
		if st.Size == 400 {
			rs = 296
		}
		lastlog = ReadLastlog(llPath, c.users.All(), rs)
		c.x.lastlogMt, c.x.lastlog = fi.ModTime(), lastlog
	}
	c.x.wtmpErr = wtmpErr
	if err == nil {
		c.x.lg.Wtmp = st
		c.x.backfill = false
		c.x.recent = mergeLogins(c.x.recent, ev.Logins, maxLogins)
		c.x.boots = mergeBoots(c.x.boots, ev.Boots, maxBoots)
	}
	if serr == nil {
		c.x.sessions = sessions
	}
	last := map[string]int64{}
	for u, t := range c.x.lastlog {
		last[u] = t
	}
	for u, t := range c.x.lg.Wtmp.Last {
		if t > last[u] {
			last[u] = t
		}
	}
	c.x.last = last
	c.saveLoginState()
}

func mergeLogins(have, add []LoginRec, n int) []LoginRec {
	if len(add) == 0 {
		return have
	}
	key := func(l LoginRec) string { return itoa64(l.At) + "|" + l.User + "|" + l.TTY }
	idx := map[string]int{}
	for i, l := range have {
		idx[key(l)] = i
	}
	for _, l := range add {
		if i, ok := idx[key(l)]; ok {
			have[i] = l
			continue
		}
		idx[key(l)] = len(have)
		have = append(have, l)
	}
	sort.SliceStable(have, func(i, j int) bool { return have[i].At < have[j].At })
	return lastN(have, n)
}

func mergeBoots(have, add []BootRec, n int) []BootRec {
	for _, b := range add {
		replaced := false
		for i := range have {
			if have[i].At == b.At {
				have[i] = b
				replaced = true
			}
		}
		if !replaced {
			have = append(have, b)
		}
	}
	sort.SliceStable(have, func(i, j int) bool { return have[i].At < have[j].At })
	return lastN(have, n)
}

// takeLogins builds the rollup's login block (nil when there is nothing new). Called with c.mu
// held, before Health resets the auth window.
func (c *Collector) takeLogins() *LoginsOut {
	if !c.cfg.On("logins") {
		return nil
	}
	o := &LoginsOut{Backfill: !c.x.loginsSent, Recent: c.x.recent, Boots: c.x.boots, Sessions: c.x.sessions}
	o.Wtmp = orStr(c.x.wtmpErr, "ok")
	if c.cfg.On("auth_log") {
		o.Auth = orStr(c.authErr, "ok")
		if !c.auth.started && c.authErr == "" {
			o.Auth = ""
		}
	}
	if o.Sessions == nil {
		o.Sessions = []SessionRec{}
	}
	sh := hashJSON(o.Sessions)
	lh := hashJSON(c.x.last)
	if lh != c.x.lastSent {
		o.Last = c.x.last
	}
	w := c.authWin
	o.Accepted = lastN(w.Logins, maxLogins)
	o.Sudo = lastN(w.Sudo, maxLogins)
	valid := map[string]bool{}
	for _, u := range c.users.All() {
		valid[u.Name] = true
	}
	for ip, n := range w.ByIP {
		f := FailedIP{IP: ip, N: n}
		if m := w.Fail[ip]; m != nil {
			f.Invalid, f.LastAt = m.Invalid, m.Last
			for u := range m.Users {
				if valid[u] && len(f.Users) < 10 {
					f.Users = append(f.Users, u)
				}
			}
			sort.Strings(f.Users)
		}
		o.Failed = append(o.Failed, f)
	}
	sort.Slice(o.Failed, func(i, j int) bool {
		if o.Failed[i].N != o.Failed[j].N {
			return o.Failed[i].N > o.Failed[j].N
		}
		return o.Failed[i].IP < o.Failed[j].IP
	})
	if len(o.Failed) > 20 {
		o.Failed = o.Failed[:20]
	}
	if c.x.loginsSent && len(o.Recent) == 0 && len(o.Boots) == 0 && o.Last == nil && len(o.Accepted) == 0 && len(o.Sudo) == 0 &&
		len(o.Failed) == 0 && sh == c.x.sessSent {
		return nil
	}
	c.x.loginsSent = true
	c.x.sessSent, c.x.lastSent = sh, lh
	c.x.recent, c.x.boots = nil, nil
	return o
}

// unitDetails refreshes what systemd says about the failed units (when the failed set changes, and
// hourly) and, for a unit that newly failed, its last log lines. Called on the worker.
func (c *Collector) unitDetails(now time.Time, list []UnitInfo, failed []string) {
	key := ""
	byName := map[string]UnitInfo{}
	for _, u := range list {
		byName[u.Name] = u
	}
	var want []UnitInfo
	for _, f := range failed {
		key += f + ","
		if u, ok := byName[f]; ok {
			want = append(want, u)
		}
	}
	c.mu.Lock()
	fresh := key != c.x.unitKey || now.Sub(c.x.unitDetAt) > time.Hour
	c.mu.Unlock()
	if !fresh {
		return
	}
	det := map[string]UnitDetail{}
	if len(want) > 0 && c.x.unitProps != nil {
		if d, err := c.x.unitProps(c.busPath, 3*time.Second, want); err == nil {
			det = d
		}
	}
	for _, u := range want { // a unit systemd would not describe still gets its name
		if _, ok := det[u.Name]; !ok {
			det[u.Name] = UnitDetail{Unit: truncate(u.Name, 120), Description: truncate(u.Description, 200)}
		}
	}
	// log lines, once per failure
	c.mu.Lock()
	var need []string
	for name, d := range det {
		if since, ok := c.x.logged[name]; !ok || since != d.Since {
			need = append(need, name)
		}
	}
	c.mu.Unlock()
	syslogErr := ""
	if len(need) > 0 && c.cfg.On("unit_logs") {
		sort.Strings(need)
		path := SyslogPath(c.host)
		tails, err := UnitLogTails(path, need)
		switch {
		case path == "":
			syslogErr = "missing"
		case err != nil && os.IsPermission(err):
			syslogErr = "unreadable"
		}
		for _, name := range need {
			d := det[name]
			d.Log = tails[name]
			det[name] = d
		}
	}
	c.mu.Lock()
	for name := range c.x.logged {
		if _, ok := det[name]; !ok {
			delete(c.x.logged, name) // recovered: a new failure gets its lines again
		}
	}
	for _, name := range need {
		c.x.logged[name] = det[name].Since
	}
	// keep log lines that were not sent yet
	for name, old := range c.x.unitDet {
		if d, ok := det[name]; ok && len(d.Log) == 0 && len(old.Log) > 0 && old.Since == d.Since {
			d.Log = old.Log
			det[name] = d
		}
	}
	c.x.unitDet, c.x.unitDetAt, c.x.unitKey, c.x.syslogErr = det, now, key, syslogErr
	c.mu.Unlock()
}

// unitDetailList: the failed units' details in the failed list's order; log lines go out once.
// Called with c.mu held.
func (c *Collector) unitDetailList(failed []string, reset bool) []UnitDetail {
	var out []UnitDetail
	for _, f := range failed {
		if d, ok := c.x.unitDet[f]; ok {
			out = append(out, d)
			if reset && len(d.Log) > 0 {
				d.Log = nil
				c.x.unitDet[f] = d
			}
		}
	}
	return out
}

// FindPortOwners runs on the worker when the set of listening sockets changed.
func (c *Collector) FindPortOwners(inodes map[uint64]bool, procs []procRef, g *Gentle) {
	c.mu.Lock()
	known := c.portOwners
	c.mu.Unlock()
	owners := FindOwners(c.proc, inodes, known, procs, c.users, c.docker, g, 200_000)
	c.mu.Lock()
	c.portOwners = owners
	c.mu.Unlock()
}

// ScanDisks runs the disk usage scan (worker).
func (c *Collector) ScanDisks(mounts []Mount, g *Gentle, now time.Time) {
	if !c.cfg.On("disk_scan") {
		return
	}
	out := c.x.disk.Scan(mounts, c.statfs, g, now)
	c.mu.Lock()
	c.x.diskOut = out
	c.mu.Unlock()
	slog.Info("disk usage scan finished", "entries", out.Entries, "took_s", out.TookS, "work_ms", out.WorkMs, "partial", out.Partial)
}

// SampleWriters reads every process's write counter (worker, once per rollup).
func (c *Collector) SampleWriters(procs []procRef, bootTime int64, g *Gentle, now time.Time) {
	if !c.cfg.On("disk_scan") {
		return
	}
	out := c.x.writers.Sample(c.proc, procs, bootTime, c.users, c.docker, g, now)
	if out == nil {
		return
	}
	c.mu.Lock()
	c.x.writersOut = out
	c.mu.Unlock()
}

// takeDisk returns (and clears) the pending disk scan and writers. Called with c.mu held.
func (c *Collector) takeDisk() (*DiskScanOut, []WriterOut) {
	d, w := c.x.diskOut, c.x.writersOut
	c.x.diskOut, c.x.writersOut = nil, nil
	return d, w
}

// MountsSnapshot: the real filesystems of the latest sample (for the worker).
func (c *Collector) MountsSnapshot() []Mount {
	out := make([]Mount, 0, len(c.mounts))
	for _, m := range c.mounts {
		if !skipMountPoint(m.Point) {
			out = append(out, m)
		}
	}
	return out
}

// InodesSnapshot copies the listening sockets' inodes (for the worker).
func (c *Collector) InodesSnapshot() map[uint64]bool {
	m := make(map[uint64]bool, len(c.portInodes))
	for k := range c.portInodes {
		m[k] = true
	}
	return m
}
