package main

// The background worker: one goroutine, pinned to one OS thread at nice 19 with idle I/O priority,
// running one task at a time (gentle.go). Tasks that can wait are postponed while the machine is
// busy (load above 0.8 per core or heavy I/O wait), for at most two hours; each task starts a few
// seconds after it was queued (jittered) so it never shares a second with the sample.

import (
	"context"
	"sort"
	"sync"
	"sync/atomic"
	"time"
)

type job struct {
	name      string
	notBefore time.Time
	queuedAt  time.Time
	in        PostureInput
	inodes    map[uint64]bool
	procs     []procRef
	mounts    []Mount
	boot      int64
}

// priority: lower runs first. Cheap and time-sensitive tasks before the long scans.
var jobPriority = map[string]int{"owners": 0, "units": 1, "auth": 2, "web": 3, "writers": 4, "posture": 5, "setuid": 6, "disk": 7}

// deferrable: may wait while the machine is busy.
var deferrable = map[string]bool{"posture": true, "setuid": true, "disk": true}

type worker struct {
	c         *Collector
	persist   bool
	mu        sync.Mutex
	pending   map[string]job
	wake      chan struct{}
	busy      atomic.Int64 // milliseconds of work since start
	postponed atomic.Int64
	sleep     func(time.Duration)
}

func newWorker(c *Collector, persist bool) *worker {
	return &worker{c: c, persist: persist, pending: map[string]job{}, wake: make(chan struct{}, 1), sleep: time.Sleep}
}

// add queues a task; one already waiting with the same name is replaced (newer snapshot).
func (w *worker) add(j job) {
	j.queuedAt = time.Now()
	w.mu.Lock()
	if old, ok := w.pending[j.name]; ok {
		j.queuedAt = old.queuedAt
	}
	w.pending[j.name] = j
	w.mu.Unlock()
	select {
	case w.wake <- struct{}{}:
	default:
	}
}

// next picks the runnable task with the best priority, or says how long to wait.
func (w *worker) next(now time.Time) (job, bool, time.Duration) {
	w.mu.Lock()
	defer w.mu.Unlock()
	busy := w.c.load.Busy()
	names := make([]string, 0, len(w.pending))
	for n := range w.pending {
		names = append(names, n)
	}
	sort.Slice(names, func(i, j int) bool { return jobPriority[names[i]] < jobPriority[names[j]] })
	wait := time.Minute
	for _, n := range names {
		j := w.pending[n]
		if now.Before(j.notBefore) {
			wait = min(wait, j.notBefore.Sub(now))
			continue
		}
		if busy && deferrable[n] && now.Sub(j.queuedAt) < 2*time.Hour {
			w.postponed.Add(1)
			j.notBefore = now.Add(10 * time.Minute)
			w.pending[n] = j
			wait = min(wait, 10*time.Minute)
			continue
		}
		delete(w.pending, n)
		return j, true, 0
	}
	return job{}, false, wait
}

func (w *worker) loop(ctx context.Context) {
	lowerThreadPriority()
	g := NewGentle(w.c.load.Busy)
	g.Sleep = w.sleep
	t := time.NewTimer(time.Second)
	defer t.Stop()
	for ctx.Err() == nil {
		j, ok, wait := w.next(time.Now())
		if !ok {
			t.Reset(max(wait, 100*time.Millisecond))
			select {
			case <-ctx.Done():
				return
			case <-w.wake:
			case <-t.C:
			}
			continue
		}
		g.Begin()
		safe("job "+j.name, func() { w.run(j, g) })
		w.busy.Add(g.Work().Milliseconds())
	}
}

func (w *worker) run(j job, g *Gentle) {
	c := w.c
	now := time.Now()
	switch j.name {
	case "setuid":
		c.ScanSetuidNow(g)
	case "web":
		c.ScanWebNow(w.persist, g)
	case "units":
		c.CheckUnits(now)
	case "auth":
		c.ReadAuthLog()
		c.ReadLogins()
	case "posture":
		c.CheckPosture(now, j.in)
	case "owners":
		c.FindPortOwners(j.inodes, j.procs, g)
	case "writers":
		c.SampleWriters(j.procs, j.boot, g, now)
	case "disk":
		c.ScanDisks(j.mounts, g, now)
	}
}
