// Command approvalens-agent: the optional Approvalens server agent.
//
// It reads /proc, /sys, statfs and a few files (crontabs, authorized_keys, sshd and sudoers
// settings, the setuid bits of binaries, the size and time of files in configured web roots, the
// auth log's SSH lines), asks systemd for its unit list over D-Bus, aggregates a sample taken
// every 60 seconds and posts compact reports to approvalens.com. It never executes commands,
// never runs code it receives, opens no listening socket and changes nothing on the machine apart
// from its own state directory.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"log/slog"
	"os"
	"os/signal"
	"runtime"
	"runtime/debug"
	"strings"
	"sync/atomic"
	"syscall"
	"time"
)

var version = "dev" // set by build.sh (-ldflags "-X main.version=...")

// Exit codes: 78 (EX_CONFIG) for a configuration error, which the systemd unit does not restart on
// (RestartPreventExitStatus=78); 70 when the watchdog finds the sampling loop stuck.
const (
	exitConfig = 78
	exitStuck  = 70
)

func usage() {
	fmt.Fprintf(os.Stderr, `approvalens-agent %s

Usage:
  approvalens-agent run [--config FILE] [--dry-run]
        sample every 60 s and report (the systemd service); with --dry-run the messages are
        printed instead of sent and no state is written
  approvalens-agent check [--config FILE]
        take one sample and print every message it would send; sends nothing
  approvalens-agent --check [--config FILE]     (also: check-config)
        validate the configuration, show the effective settings and what is skipped here
  approvalens-agent --version                   (also: version)

Config: %s. Documentation: https://approvalens.com/agent
`, version, DefaultConfigPath)
}

func main() {
	setupLogging()
	if len(os.Args) < 2 {
		usage()
		os.Exit(2)
	}
	cmd, args := os.Args[1], os.Args[2:]
	switch cmd {
	case "--check", "-check":
		cmd = "check-config"
	case "--dry-run", "-dry-run":
		cmd, args = "run", append([]string{"--dry-run"}, args...)
	case "--version", "-version", "-v":
		cmd = "version"
	case "--help", "-help", "-h", "help":
		usage()
		return
	}
	fs := flag.NewFlagSet(cmd, flag.ContinueOnError)
	cfgPath := fs.String("config", envOr("APPROVALENS_AGENT_CONFIG", DefaultConfigPath), "config file")
	dry := fs.Bool("dry-run", false, "print the messages instead of sending them")
	switch cmd {
	case "version":
		fmt.Printf("approvalens-agent %s (%s, %s/%s)\n", version, runtime.Version(), runtime.GOOS, runtime.GOARCH)
		return
	case "run", "check", "check-config":
		if err := fs.Parse(args); err != nil {
			os.Exit(2)
		}
		if fs.NArg() > 0 {
			fmt.Fprintf(os.Stderr, "unexpected argument %q\n", fs.Arg(0))
			os.Exit(2)
		}
	default:
		usage()
		os.Exit(2)
	}
	switch cmd {
	case "run":
		os.Exit(run(*cfgPath, *dry))
	case "check":
		os.Exit(check(*cfgPath))
	case "check-config":
		os.Exit(checkConfig(*cfgPath))
	}
}

func envOr(k, d string) string {
	if v := os.Getenv(k); v != "" {
		return v
	}
	return d
}

// Bounded footprint: two OS threads run Go code at most, a soft memory limit well under the
// unit's MemoryMax, and an eager GC.
func tuneRuntime() {
	runtime.GOMAXPROCS(2)
	debug.SetGCPercent(50)
	debug.SetMemoryLimit(24 << 20)
}

var panicCount atomic.Int64

// safe runs fn and turns a panic into a logged error: one bad reading never stops the agent.
func safe(name string, fn func()) (ok bool) {
	defer func() {
		if r := recover(); r != nil {
			panicCount.Add(1)
			logLimited("panic:"+name, 15*time.Minute, slog.LevelError, "internal error recovered", "in", name, "panic", fmt.Sprint(r),
				"stack", string(debug.Stack()))
			ok = false
		}
	}()
	fn()
	return true
}

func safeBool(name string, fn func() bool) (res bool) {
	if !safe(name, func() { res = fn() }) {
		return false
	}
	return res
}

// watchdog exits the process when the sampling loop has not made progress for `limit` (a read
// of /proc or statfs() hanging on a sick device). systemd then restarts the agent.
func watchdog(beat *atomic.Int64, base time.Time, limit time.Duration) {
	t := time.NewTicker(limit / 4)
	defer t.Stop()
	for range t.C {
		if stuck := time.Since(base) - time.Duration(beat.Load()); stuck > limit {
			buf := make([]byte, 32<<10)
			n := runtime.Stack(buf, true)
			slog.Error("the sampling loop is stuck; exiting so that systemd restarts the agent", "stuck_for", stuck.Round(time.Second).String(),
				"goroutines", string(buf[:n]))
			os.Exit(exitStuck)
		}
	}
}

func run(path string, dry bool) int {
	tuneRuntime()
	cfg, err := LoadConfig(path)
	if err != nil {
		slog.Error("cannot start: configuration error (fix it, then: systemctl restart approvalens-agent)", "err", err)
		return exitConfig
	}
	for _, w := range cfg.Warnings {
		slog.Warn(w)
	}
	c := NewCollector(cfg, version)
	o := NewOutbox(c, !dry)
	s := NewSender(cfg, version)
	if dry {
		s.Dry = os.Stdout
	}
	s.OnResync = o.Resync
	s.LoadSpool()
	if !dry {
		c.LoadWebState()
	}
	c.LoadLoginState(!dry)

	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()
	signal.Ignore(syscall.SIGHUP, syscall.SIGPIPE)
	sendDone := make(chan struct{})
	go func() {
		defer close(sendDone)
		for ctx.Err() == nil {
			safe("sender", func() { s.Run(ctx) })
		}
	}()

	slog.Info("agent started", "version", version, "url", cfg.URL, "uid", os.Geteuid(), "sample", cfg.SampleInterval.String(),
		"heartbeat", cfg.HeartbeatInterval.String(), "rollup", cfg.RollupInterval.String(), "spooled", s.Pending(), "dry_run", dry)
	if d := c.Disabled(); len(d) > 0 {
		slog.Info("checks disabled in the config", "checks", strings.Join(d, ","))
	}

	// Everything heavier than the sample runs on ONE background worker (gentle mode, gentle.go),
	// one task at a time, so a sample is never late and the agent never makes a burst. A task that
	// is already queued is not queued twice.
	w := newWorker(c, !dry)
	go w.loop(ctx)
	queue := func(name string) {
		j := job{name: name, notBefore: time.Now().Add(jitter(20*time.Second, 0.75))} // never on the sample's second
		switch name {
		case "posture":
			j.in = c.PostureSnapshot()
		case "owners":
			j.inodes, j.procs = c.InodesSnapshot(), c.procRefs()
			j.notBefore = time.Now().Add(2 * time.Second)
		case "writers":
			j.procs, j.boot = c.procRefs(), c.hostInfo.BootTime
		case "disk":
			j.mounts = c.MountsSnapshot()
		}
		w.add(j)
	}

	base := time.Now()
	var beat atomic.Int64
	go watchdog(&beat, base, max(4*cfg.SampleInterval, 10*time.Minute))

	tick := time.NewTicker(cfg.SampleInterval)
	defer tick.Stop()
	start := time.Now()
	safe("first sample", func() {
		c.Sample(start)
		o.RefreshInventory()
	})
	queue("units")
	queue("auth")
	queue("posture")
	if c.ownersWant {
		c.ownersWant = false
		queue("owners")
	}
	safe("first messages", func() {
		s.Enqueue(o.Heartbeat(start.UTC(), s.Pending())) // the account shows "connected" right away
		if o.NeedFull() {
			s.Enqueue(o.Full(start.UTC()))
		}
	})
	nextHB := start.Add(cfg.HeartbeatInterval)
	nextRollup := start.Add(time.Minute) // the first chart points soon after install, then every 15 min
	nextInv := start.Add(cfg.HeartbeatInterval)
	nextSetuid := start.Add(jitter(5*time.Minute, 0.5))
	nextWeb := start
	nextChecks := start.Add(cfg.HeartbeatInterval)
	nextPosture := start.Add(jitter(time.Hour, 0.1))
	nextDisk := start.Add(jitter(15*time.Minute, 0.5))
	lastStats := start

	step := func(now time.Time) {
		c.Sample(now)
		if c.ownersWant {
			c.ownersWant = false
			queue("owners")
		}
		if !now.Before(nextSetuid) {
			nextSetuid = now.Add(jitter(cfg.SetuidInterval, 0.1))
			queue("setuid")
		}
		if !now.Before(nextDisk) {
			nextDisk = now.Add(jitter(6*time.Hour, 0.1))
			queue("disk")
		}
		if len(cfg.WebRoots) > 0 && !now.Before(nextWeb) {
			nextWeb = now.Add(cfg.WebRootInterval)
			queue("web")
		}
		if !now.Before(nextChecks) {
			nextChecks = now.Add(cfg.HeartbeatInterval)
			queue("units")
			queue("auth")
		}
		if !now.Before(nextPosture) {
			nextPosture = now.Add(jitter(time.Hour, 0.1))
			queue("posture")
		}
		if !now.Before(nextInv) { // crontabs and SSH keys: read every heartbeat interval
			nextInv = now.Add(cfg.HeartbeatInterval)
			o.RefreshInventory()
		}
		utc := now.UTC()
		if o.NeedFull() {
			o.RefreshInventory()
			s.Enqueue(o.Full(utc))
		}
		if m := o.Event(utc, cfg.EventGap); m != nil {
			s.Enqueue(*m)
		}
		if !now.Before(nextRollup) {
			nextRollup = now.Add(cfg.RollupInterval)
			s.Enqueue(o.Rollup(utc))
			queue("writers") // read the write counters now: their difference goes into the next rollup
		}
		if !now.Before(nextHB) {
			nextHB = now.Add(cfg.HeartbeatInterval)
			s.Enqueue(o.Heartbeat(utc, s.Pending()))
		}
		if now.Sub(lastStats) >= 24*time.Hour {
			msgs, bytes := s.Sent()
			slog.Info("daily statistics", "messages", msgs, "bytes", bytes, "spooled", s.Pending(), "dropped", s.dropped.Load(),
				"recovered_errors", panicCount.Load(), "worker_busy_ms", w.busy.Load(), "postponed", w.postponed.Load())
			lastStats = now
		}
	}

	for {
		select {
		case <-ctx.Done():
			tick.Stop()
			stop()
			<-sendDone
			s.FinalFlush(5 * time.Second)
			msgs, bytes := s.Sent()
			slog.Info("stopping", "messages_sent", msgs, "bytes_sent", bytes, "left_in_spool", s.Pending())
			return 0
		case now := <-tick.C:
			beat.Store(int64(time.Since(base)))
			safe("sample", func() { step(now) })
		}
	}
}

// check prints the messages the agent would send now. Nothing is sent and no state is written.
func check(path string) int {
	cfg, err := LoadConfig(path)
	if err != nil {
		// Transparency first: show what would be collected even without a valid config.
		fmt.Fprintf(os.Stderr, "config: %v (continuing with defaults; nothing is sent by `check` anyway)\n", err)
		cfg = DefaultConfig()
		cfg.path = path
	}
	lowerThreadPriority()
	c := NewCollector(cfg, version)
	c.LoadWebState()
	c.LoadLoginState(false) // reads history (backfill), saves nothing
	o := NewOutbox(c, false)
	c.Sample(time.Now())
	c.SampleWriters(c.procRefs(), c.hostInfo.BootTime, nil, time.Now())
	c.FindPortOwners(c.InodesSnapshot(), c.procRefs(), nil)
	time.Sleep(2 * time.Second) // a second sample turns counters into rates
	c.Sample(time.Now())
	c.SampleWriters(c.procRefs(), c.hostInfo.BootTime, nil, time.Now())
	c.ScanSetuidNow(nil)
	c.ScanWebNow(false, nil)
	c.CheckUnits(time.Now())
	c.ReadAuthLog() // positions at the end (the history goes into the login block); failures are counted from now on
	c.ReadLogins()
	c.CheckPosture(time.Now(), c.PostureSnapshot())
	c.x.disk.MaxWork, c.x.disk.MaxWall = 5*time.Second, time.Minute // `check` shows a shortened disk scan
	c.ScanDisks(c.MountsSnapshot(), nil, time.Now())
	o.RefreshInventory()
	now := time.Now().UTC()
	msgs := []any{o.Heartbeat(now, 0), o.Full(now), o.Rollup(now)}
	if m := o.Event(now, 0); m != nil {
		msgs = append(msgs, *m)
	}
	total := 0
	for _, m := range msgs {
		b, _ := json.MarshalIndent(m, "", "  ")
		gz, _ := Encode(m)
		total += len(gz)
		fmt.Println(string(b))
		fmt.Fprintf(os.Stderr, "-- %s: %d bytes gzip (%d bytes JSON)\n", msgKind(m), len(gz), len(b))
	}
	fmt.Fprintf(os.Stderr, "\nWould POST these to %s with token %s. Schedule: heartbeat every %s, rollup every %s, events at once (at most one per %s), the full inventory only after install, an upgrade or when the server asks for a resync.\n",
		cfg.Endpoint(), maskToken(cfg.Token), cfg.HeartbeatInterval, cfg.RollupInterval, cfg.EventGap)
	fmt.Fprintf(os.Stderr, "Running as uid %d, mode %s (capabilities: %s). Checks skipped here: %s. Disabled in the config: %s\n", os.Geteuid(),
		c.ident.Mode, joinOr(c.ident.Caps, "none"), joinOr(c.Skipped(), "none"), joinOr(c.Disabled(), "none"))
	fmt.Fprintln(os.Stderr, "Nothing was sent. The agent never executes commands and has no listening socket.")
	return 0
}

// checkConfig validates the configuration and shows what the agent will do with it.
func checkConfig(path string) int {
	cfg, err := LoadConfig(path)
	if err != nil {
		fmt.Fprintf(os.Stderr, "config error: %v\n", err)
		return exitConfig
	}
	fmt.Printf("%s: OK\n", path)
	fmt.Printf("  reports to      %s (token %s)\n", cfg.Endpoint(), maskToken(cfg.Token))
	fmt.Printf("  schedule        sample %s, heartbeat %s, rollup %s, events at most one per %s\n", cfg.SampleInterval, cfg.HeartbeatInterval,
		cfg.RollupInterval, cfg.EventGap)
	fmt.Printf("  web roots       %s\n", joinOr(cfg.WebRoots, "none"))
	c := NewCollector(cfg, version)
	fmt.Printf("  disabled        %s\n", joinOr(c.Disabled(), "none"))
	fmt.Printf("  auth log        %s\n", orStr(c.auth.Path, "none found"))
	fmt.Printf("  state dir       %s (%s)\n", cfg.StateDir, dirState(cfg.StateDir))
	fmt.Printf("  running as      uid %d, mode %s (capabilities: %s)\n", os.Geteuid(), c.ident.Mode, joinOr(c.ident.Caps, "none"))
	for _, w := range cfg.Warnings {
		fmt.Printf("warning: %s\n", w)
	}
	return 0
}

func dirState(p string) string {
	fi, err := os.Stat(p)
	switch {
	case errors.Is(err, os.ErrNotExist):
		return "created by systemd when the service starts"
	case err != nil:
		return err.Error()
	case !fi.IsDir():
		return "not a directory"
	}
	f, err := os.CreateTemp(p, ".check-*")
	if err != nil {
		return "not writable by this user"
	}
	f.Close()
	os.Remove(f.Name())
	return "writable"
}

func maskToken(t string) string {
	if len(t) > 9 {
		return t[:9] + "…"
	}
	return t
}

func orStr(s, d string) string {
	if s == "" {
		return d
	}
	return s
}

func joinOr(xs []string, d string) string {
	if len(xs) == 0 {
		return d
	}
	return strings.Join(xs, ", ")
}
