package main

// Gentle mode: the agent must never be noticed. Everything heavier than the one-minute sample (the
// port owner search, the login history, the hourly settings check, the disk usage scan, the
// per-process write counters) runs on ONE background worker, one task at a time, on a thread with
// the lowest CPU priority (nice 19) and idle I/O priority. Inside a task the work is cut into
// slices of about 2 ms; after each slice the worker sleeps so that it uses about 1% of one core
// while it works, and four times less while the machine is busy (load above 0.8 per core or a
// lot of I/O wait). Tasks that can wait (the disk scan, the setuid scan, the settings check) are
// postponed while the machine is busy, up to two hours.

import (
	"math/rand"
	"sync/atomic"
	"time"
)

type Gentle struct {
	Slice time.Duration // work before a pause
	Pause time.Duration // pause after a slice (4x while the host is busy)
	Busy  func() bool
	Sleep func(time.Duration)
	start time.Time
	work  time.Duration
	n     int
}

// NewGentle: 2 ms slices, 200 ms pauses: about 1% of one core while a task runs.
func NewGentle(busy func() bool) *Gentle {
	return &Gentle{Slice: 2 * time.Millisecond, Pause: 200 * time.Millisecond, Busy: busy, Sleep: time.Sleep}
}

// Begin starts timing a task.
func (g *Gentle) Begin() {
	if g == nil {
		return
	}
	g.start, g.work, g.n = time.Now(), 0, 0
}

// Tick is called in the loops of a task; every few calls it checks the time spent since the last
// pause and pauses when the slice is used up.
func (g *Gentle) Tick() {
	if g == nil {
		return
	}
	g.n++
	if g.n&3 != 0 { // the clock is looked at every 4 steps: a slice overshoots little
		return
	}
	el := time.Since(g.start)
	if el < g.Slice {
		return
	}
	g.work += el
	p := g.Pause
	if g.Busy != nil && g.Busy() {
		p *= 4
	}
	if g.Sleep != nil {
		g.Sleep(p)
	}
	g.start = time.Now()
}

// Work is the time spent working (pauses excluded) since Begin.
func (g *Gentle) Work() time.Duration {
	if g == nil {
		return 0
	}
	return g.work + time.Since(g.start)
}

// HostLoad is what the sampling loop knows about how busy the machine is, for the worker.
type HostLoad struct {
	perCore atomic.Uint64 // load1 / cores, x1000
	iowait  atomic.Uint64 // % of CPU time in I/O wait over the last sample, x10
}

func (h *HostLoad) Set(load1 float64, cores int, iowaitPct float64) {
	if cores < 1 {
		cores = 1
	}
	h.perCore.Store(uint64(max(0, load1/float64(cores)*1000)))
	h.iowait.Store(uint64(max(0, iowaitPct*10)))
}

// Busy: load above 0.8 per core, or more than 20% of CPU time waiting for I/O.
func (h *HostLoad) Busy() bool {
	return h.perCore.Load() > 800 || h.iowait.Load() > 200
}

// jitter returns d plus or minus up to frac of it (timers never line up on the same second).
func jitter(d time.Duration, frac float64) time.Duration {
	if d <= 0 || frac <= 0 {
		return d
	}
	j := time.Duration((rand.Float64()*2 - 1) * frac * float64(d))
	return d + j
}
