package main

import (
	"bufio"
	"bytes"
	"errors"
	"fmt"
	"net"
	"net/url"
	"os"
	"regexp"
	"sort"
	"strconv"
	"strings"
	"time"
)

const DefaultConfigPath = "/etc/approvalens-agent.yaml"

// Checks that can be switched off with `disable: [...]`.
var checkNames = map[string]string{
	"cmdline":  "command lines of the top processes (names, users and paths are still sent)",
	"auth_log": "SSH login failures counted from /var/log/auth.log or /var/log/secure",
	"systemd":  "failed systemd units and the state of firewall / update / time services (read over D-Bus)",
	"posture":  "the daily security settings check (sshd, firewall, automatic updates, sudoers, UID 0, exposed databases)",
	"crontabs": "crontab lines",
	"ssh_keys": "SSH key fingerprints",
	"setuid":   "the setuid / setgid file scan",
	// 0.3.0
	"logins":       "login history (wtmp, utmp, lastlog) and the logins and sudo use counted from the auth log",
	"disk_scan":    "the disk usage scan (directory and file sizes, a few times a day) and the per-process disk writes",
	"unit_logs":    "the last log lines of a unit that failed (from /var/log/syslog or /var/log/messages)",
	"reachability": "nothing on the server: asks Approvalens not to test from outside whether the public ports answer",
}

// Config is /etc/approvalens-agent.yaml. Only a small YAML subset is read: `key: value`
// lines and lists written as `- item` lines under a key (or `[a, b]`).
type Config struct {
	Token             string
	URL               string
	WebRoots          []string
	WebRootExclude    []string
	WebRootMaxFiles   int
	SampleInterval    time.Duration
	HeartbeatInterval time.Duration
	RollupInterval    time.Duration
	EventGap          time.Duration
	SetuidInterval    time.Duration
	WebRootInterval   time.Duration
	StateDir          string
	AuthLog           string          // "" = auto (/var/log/auth.log, then /var/log/secure)
	Disabled          map[string]bool // check name -> off
	Warnings          []string        // not fatal: shown by --check and logged at start
	path              string
}

func DefaultConfig() Config {
	return Config{
		URL:               "https://approvalens.com",
		WebRootMaxFiles:   20000,
		SampleInterval:    60 * time.Second,
		HeartbeatInterval: 5 * time.Minute,
		RollupInterval:    15 * time.Minute,
		EventGap:          60 * time.Second,
		SetuidInterval:    6 * time.Hour,
		WebRootInterval:   15 * time.Minute,
		StateDir:          "/var/lib/approvalens-agent",
		Disabled:          map[string]bool{},
	}
}

// On reports whether a check is enabled.
func (c Config) On(check string) bool { return !c.Disabled[check] }

// LoadConfig reads, parses and validates the config file. Every error names the file and,
// for syntax errors, the line.
func LoadConfig(path string) (Config, error) {
	c := DefaultConfig()
	c.path = path
	b, err := os.ReadFile(path)
	if err != nil {
		if errors.Is(err, os.ErrNotExist) {
			return c, fmt.Errorf("%s does not exist (install the agent with the line from your Approvalens account)", path)
		}
		if errors.Is(err, os.ErrPermission) {
			return c, fmt.Errorf("%s is not readable by uid %d (it must be owned by the agent's user, mode 0600)", path, os.Geteuid())
		}
		return c, err
	}
	if err := c.parse(b); err != nil {
		return c, fmt.Errorf("%s: %w", path, err)
	}
	if env := os.Getenv("APPROVALENS_AGENT_TOKEN"); env != "" {
		c.Token = env
	}
	if fi, err := os.Stat(path); err == nil && fi.Mode().Perm()&0o004 != 0 {
		c.Warnings = append(c.Warnings, fmt.Sprintf("%s is readable by every user and holds the token: chmod 600 %s", path, path))
	}
	if err := c.Validate(); err != nil {
		return c, fmt.Errorf("%s: %w", path, err)
	}
	return c, nil
}

var scalarKeys = map[string]bool{"token": true, "url": true, "web_root_max_files": true, "sample_interval": true, "heartbeat_interval": true,
	"rollup_interval": true, "event_min_gap": true, "setuid_interval": true, "web_root_interval": true, "state_dir": true, "auth_log": true}
var listKeys = map[string]bool{"web_roots": true, "web_root_exclude": true, "disable": true}

func (c *Config) parse(b []byte) error {
	sc := bufio.NewScanner(bytes.NewReader(b))
	sc.Buffer(make([]byte, 64*1024), 1024*1024)
	listKey := ""
	seen := map[string]int{}
	n := 0
	for sc.Scan() {
		n++
		raw := sc.Text()
		if n == 1 {
			raw = strings.TrimPrefix(raw, "\xef\xbb\xbf") // a BOM from a Windows editor
		}
		line := strings.TrimSpace(stripComment(raw))
		if line == "" {
			continue
		}
		if strings.HasPrefix(line, "- ") || line == "-" {
			if listKey == "" {
				return fmt.Errorf("line %d: list item without a key above it", n)
			}
			if err := c.set(listKey, unquote(strings.TrimSpace(strings.TrimPrefix(line, "-")))); err != nil {
				return fmt.Errorf("line %d: %w", n, err)
			}
			continue
		}
		k, v, ok := strings.Cut(line, ":")
		if !ok {
			return fmt.Errorf("line %d: expected `key: value`, got %q", n, truncate(line, 60))
		}
		k, v = strings.TrimSpace(k), strings.TrimSpace(v)
		if err := knownKey(k); err != nil {
			return fmt.Errorf("line %d: %w", n, err)
		}
		if prev, dup := seen[k]; dup && scalarKeys[k] { // 0.1.0 took the later value silently; keep that, but say so
			c.Warnings = append(c.Warnings, fmt.Sprintf("line %d: %s is already set on line %d; the later value is used", n, k, prev))
		}
		seen[k] = n
		listKey = ""
		if v == "" {
			if !listKeys[k] {
				return fmt.Errorf("line %d: %s needs a value", n, k)
			}
			listKey = k
			continue
		}
		if strings.HasPrefix(v, "[") && strings.HasSuffix(v, "]") {
			if !listKeys[k] {
				return fmt.Errorf("line %d: %s takes one value, not a list", n, k)
			}
			for _, item := range strings.Split(strings.Trim(v, "[]"), ",") {
				if item = unquote(strings.TrimSpace(item)); item != "" {
					if err := c.set(k, item); err != nil {
						return fmt.Errorf("line %d: %w", n, err)
					}
				}
			}
			continue
		}
		if err := c.set(k, unquote(v)); err != nil {
			return fmt.Errorf("line %d: %w", n, err)
		}
	}
	return sc.Err()
}

func knownKey(k string) error {
	if scalarKeys[k] || listKeys[k] {
		return nil
	}
	var all []string
	for x := range scalarKeys {
		all = append(all, x)
	}
	for x := range listKeys {
		all = append(all, x)
	}
	sort.Strings(all)
	best, bestD := "", 4
	for _, x := range all {
		if d := editDistance(k, x); d < bestD {
			best, bestD = x, d
		}
	}
	if best != "" {
		return fmt.Errorf("unknown key %q (did you mean %q?)", k, best)
	}
	return fmt.Errorf("unknown key %q (known keys: %s)", k, strings.Join(all, ", "))
}

func editDistance(a, b string) int {
	prev := make([]int, len(b)+1)
	cur := make([]int, len(b)+1)
	for j := range prev {
		prev[j] = j
	}
	for i := 1; i <= len(a); i++ {
		cur[0] = i
		for j := 1; j <= len(b); j++ {
			cost := 1
			if a[i-1] == b[j-1] {
				cost = 0
			}
			cur[j] = min(prev[j]+1, cur[j-1]+1, prev[j-1]+cost)
		}
		prev, cur = cur, prev
	}
	return prev[len(b)]
}

func stripComment(s string) string {
	inQ := byte(0)
	for i := 0; i < len(s); i++ {
		ch := s[i]
		switch {
		case inQ != 0 && ch == inQ:
			inQ = 0
		case inQ == 0 && (ch == '"' || ch == '\''):
			inQ = ch
		case inQ == 0 && ch == '#' && (i == 0 || s[i-1] == ' ' || s[i-1] == '\t'):
			return s[:i]
		}
	}
	return s
}

func unquote(s string) string {
	if len(s) >= 2 && (s[0] == '"' && s[len(s)-1] == '"' || s[0] == '\'' && s[len(s)-1] == '\'') {
		return s[1 : len(s)-1]
	}
	return s
}

func (c *Config) set(k, v string) error {
	switch k {
	case "token":
		c.Token = v
	case "url":
		c.URL = strings.TrimRight(v, "/")
	case "web_roots":
		c.WebRoots = append(c.WebRoots, v)
	case "web_root_exclude":
		c.WebRootExclude = append(c.WebRootExclude, v)
	case "disable":
		v = strings.ToLower(v)
		if _, ok := checkNames[v]; !ok {
			names := make([]string, 0, len(checkNames))
			for n := range checkNames {
				names = append(names, n)
			}
			sort.Strings(names)
			return fmt.Errorf("disable: unknown check %q (known: %s)", v, strings.Join(names, ", "))
		}
		c.Disabled[v] = true
	case "auth_log":
		if v != "auto" && !strings.HasPrefix(v, "/") {
			return fmt.Errorf("auth_log: %q is not an absolute path (or `auto`)", v)
		}
		if v == "auto" {
			v = ""
		}
		c.AuthLog = v
	case "web_root_max_files":
		n, err := strconv.Atoi(v)
		if err != nil || n < 1 || n > 1_000_000 {
			return fmt.Errorf("web_root_max_files: %q is not a number between 1 and 1000000", v)
		}
		c.WebRootMaxFiles = n
	case "sample_interval", "heartbeat_interval", "rollup_interval", "event_min_gap", "setuid_interval", "web_root_interval":
		d, err := parseDuration(v)
		if err != nil {
			return fmt.Errorf("%s: %q is not a duration (write 60s, 5m or 6h)", k, v)
		}
		switch k {
		case "sample_interval":
			c.SampleInterval = d
		case "heartbeat_interval":
			c.HeartbeatInterval = d
		case "rollup_interval":
			c.RollupInterval = d
		case "event_min_gap":
			c.EventGap = d
		case "setuid_interval":
			c.SetuidInterval = d
		case "web_root_interval":
			c.WebRootInterval = d
		}
	case "state_dir":
		c.StateDir = v
	default:
		return knownKey(k)
	}
	return nil
}

// parseDuration accepts Go durations ("90s", "5m", "6h") or plain seconds.
func parseDuration(v string) (time.Duration, error) {
	if n, err := strconv.Atoi(v); err == nil {
		return time.Duration(n) * time.Second, nil
	}
	return time.ParseDuration(v)
}

// The token format the web app accepts (web/app/api/agent/v1/report/route.ts).
var tokenRe = regexp.MustCompile(`^alsa_[A-Za-z0-9_-]{20,90}$`)

func (c Config) Validate() error {
	if c.Token == "" {
		return errors.New("token is missing (copy the install line from your Approvalens account)")
	}
	if !tokenRe.MatchString(c.Token) {
		return errors.New("token does not look like an Approvalens server token (alsa_ followed by 20-90 letters, digits, - or _)")
	}
	u, err := url.Parse(c.URL)
	if err != nil || u.Host == "" {
		return fmt.Errorf("url %q is not valid", c.URL)
	}
	if u.User != nil || u.RawQuery != "" || u.Fragment != "" {
		return fmt.Errorf("url %q must not carry a user, a query or a fragment", c.URL)
	}
	// Plain HTTP only to this machine (local testing); anything else must be HTTPS.
	if u.Scheme != "https" {
		host := u.Hostname()
		ip := net.ParseIP(host)
		if u.Scheme != "http" || !(host == "localhost" || (ip != nil && ip.IsLoopback())) {
			return fmt.Errorf("url must be https:// (got %q)", c.URL)
		}
	}
	if c.SampleInterval < 5*time.Second || c.SampleInterval > 10*time.Minute {
		return fmt.Errorf("sample_interval must be between 5s and 10m (got %s)", c.SampleInterval)
	}
	if c.HeartbeatInterval < 30*time.Second || c.HeartbeatInterval > 10*time.Minute || c.HeartbeatInterval < c.SampleInterval {
		return fmt.Errorf("heartbeat_interval must be between 30s and 10m, and not shorter than sample_interval (got %s)", c.HeartbeatInterval)
	}
	if c.RollupInterval < c.HeartbeatInterval || c.RollupInterval > time.Hour {
		return fmt.Errorf("rollup_interval must be between heartbeat_interval and 1h (got %s)", c.RollupInterval)
	}
	if c.EventGap < 10*time.Second || c.EventGap > 10*time.Minute {
		return fmt.Errorf("event_min_gap must be between 10s and 10m (got %s)", c.EventGap)
	}
	if c.SetuidInterval < time.Minute {
		return fmt.Errorf("setuid_interval must be at least 1m (got %s)", c.SetuidInterval)
	}
	if c.WebRootInterval < time.Minute {
		return fmt.Errorf("web_root_interval must be at least 1m (got %s)", c.WebRootInterval)
	}
	for _, r := range c.WebRoots {
		if !strings.HasPrefix(r, "/") {
			return fmt.Errorf("web_roots: %q is not an absolute path", r)
		}
	}
	if !strings.HasPrefix(c.StateDir, "/") {
		return fmt.Errorf("state_dir: %q is not an absolute path", c.StateDir)
	}
	return nil
}

// Endpoint the reports go to.
func (c Config) Endpoint() string { return c.URL + "/api/agent/v1/report" }
