#!/usr/bin/env python3
"""Checkmk special agent for OPNsense (REST API).

Polls an OPNsense firewall over its REST API using Basic auth (API key as
username, API secret as password) and emits Checkmk agent sections:

    <<<opnsense_firmware:sep(0)>>>   JSON from core/firmware/status
    <<<opnsense_services:sep(0)>>>   JSON list from core/service/search
    <<<opnsense_system:sep(0)>>>     JSON: system/status + diagnostics gauges
    <<<opnsense_smart:sep(0)>>>      JSON: SMART data per disk (os-smart)
    <<<opnsense_gateways:sep(0)>>>   JSON from routes/gateway/status
    <<<opnsense_wireguard:sep(0)>>>  JSON from wireguard/service/show
    <<<opnsense_dhcp:sep(0)>>>       JSON: Kea + Dnsmasq DHCPv4 ranges/leases
    <<<opnsense_audit:sep(0)>>>      JSON: result of core/firmware/audit

All endpoints only read data, with two throttled exceptions that start an
action on the firewall:
  - the firmware update check (POST core/firmware/status runs "firmware
    probe", which contacts the package mirrors). It runs at most once per
    --firmware-check-interval minutes (default 120), plus once right away if
    OPNsense has no check result yet (e.g. after a reboot). All other runs
    only read the cached result (GET). 0 never triggers a check.
  - the package audit (POST core/firmware/audit runs "pkg audit"). It runs at
    most once per --audit-interval minutes; the result is cached on the
    Checkmk site. --audit-interval 0 disables it.
Both write to the same firmware progress log on OPNsense, so no update check
is triggered while an audit is still running.

Required privileges of the API user (exact names from OPNsense ACL.xml):
    "Status: Services", "Lobby: Dashboard",
    "System: Status"                         - base sections
    "System: Firmware"                       - firmware status + audit
    "Services: SMART"                        - SMART (os-smart plugin)
    "System: Gateways"                       - gateways
    "VPN: WireGuard: Status"                 - WireGuard peers
    "Services: DHCP: Kea(v4)"                - DHCP pool usage (Kea)
    "Services: Dnsmasq DNS/DHCP: Settings"   - DHCP pool usage (Dnsmasq)
Missing privileges / plugins only blank out the affected section.
WARNING: OPNsense privileges have no read/write split - all of the above
except "Lobby: Dashboard" also allow write actions (e.g. firmware update,
reboot, service start/stop, config changes). See README.
"""
import argparse
import base64
import json
import os
import re
import ssl
import sys
import tempfile
import time
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen


def parse_args(argv):
    p = argparse.ArgumentParser(description="Checkmk OPNsense special agent")
    p.add_argument("--api-key", required=True, help="OPNsense API key")
    p.add_argument("--api-secret", required=True, help="OPNsense API secret")
    p.add_argument("--port", type=int, default=8443, help="HTTPS port (default 8443)")
    p.add_argument("--no-cert-check", action="store_true",
                   help="Disable TLS certificate verification (self-signed)")
    p.add_argument("--timeout", type=int, default=20, help="Per-request timeout (s)")
    p.add_argument("--audit-interval", type=int, default=360,
                   help="Run the package audit every N minutes (0 = off, default 360)")
    p.add_argument("--firmware-check-interval", type=int, default=120,
                   help="Trigger a firmware update check every N minutes "
                        "(0 = never, only read the cached result; default 120)")
    p.add_argument("hostname", help="OPNsense host / address")
    return p.parse_args(argv)


def make_context(no_cert_check):
    ctx = ssl.create_default_context()
    if no_cert_check:
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
    return ctx


class OPNsenseClient:
    def __init__(self, host, port, key, secret, ctx, timeout):
        # Bracket bare IPv6 addresses for the URL authority component.
        if ":" in host and not host.startswith("["):
            host = "[%s]" % host
        self.base = "https://%s:%d/api" % (host, port)
        self.ctx = ctx
        self.timeout = timeout
        token = base64.b64encode(("%s:%s" % (key, secret)).encode()).decode()
        self.auth = "Basic %s" % token

    def call(self, path, method="GET", form=None):
        url = "%s/%s" % (self.base, path)
        if method == "POST" and form is not None:
            data = urlencode(form).encode("utf-8")
        elif method == "POST":
            data = b""
        else:
            data = None
        req = Request(url, data=data, method=method)
        req.add_header("Authorization", self.auth)
        if form is not None:
            req.add_header("Content-Type", "application/x-www-form-urlencoded")
        with urlopen(req, context=self.ctx, timeout=self.timeout) as resp:
            return json.loads(resp.read().decode("utf-8"))


def emit(section, payload):
    sys.stdout.write("<<<%s:sep(0)>>>\n" % section)
    sys.stdout.write(json.dumps(payload) + "\n")


def _try(client, path, method="GET", form=None):
    """Call an endpoint; on failure return {"_error": ..., "_code": ...}."""
    try:
        return client.call(path, method=method, form=form)
    except HTTPError as exc:
        return {"_error": str(exc), "_code": exc.code}
    except (URLError, ValueError, OSError) as exc:
        return {"_error": str(exc)}


def _rows(payload):
    if isinstance(payload, dict) and isinstance(payload.get("rows"), list):
        return payload["rows"]
    return []


# --- DHCP -----------------------------------------------------------------
def _enabled_service_ids(services):
    """Ids from core/service/search, or None if the list is unavailable.

    OPNsense lists a service there only if it is enabled (kea.inc,
    dnsmasq.inc), e.g. "kea-dhcp/v4" or "dnsmasq".
    """
    # An empty list (e.g. configd not answering) counts as unavailable: a
    # running OPNsense always has services.
    if not isinstance(services, dict) or "_error" in services \
            or not isinstance(services.get("rows"), list) \
            or not services["rows"]:
        return None
    return {r.get("id") for r in services["rows"] if isinstance(r, dict)}


def collect_dhcp(client, services=None):
    """Kea + Dnsmasq: configured DHCPv4 ranges and active leases.

    Leases are reduced to address (+ Kea state) to keep the section small.
    A backend is only queried if its service is enabled: the lease queries
    are expensive on OPNsense (MAC table, DHCP options) even if the server
    is not in use. Without a usable service list both are queried.
    """
    result = {}
    enabled = _enabled_service_ids(services)
    if enabled is None or "kea-dhcp/v4" in enabled:
        _collect_kea(client, result)
    if enabled is None or "dnsmasq" in enabled:
        _collect_dnsmasq(client, result)
    return result


def _collect_kea(client, result):
    subnets = _try(client, "kea/dhcpv4/search_subnet")
    if "_error" in subnets:
        result["kea"] = {"_error": subnets["_error"], "_code": subnets.get("_code")}
    else:
        leases = _try(client, "kea/leases4/search")
        kea = {
            "subnets": [
                {"subnet": r.get("subnet", ""), "pools": r.get("pools", ""),
                 "description": r.get("description", "")}
                for r in _rows(subnets)
            ],
        }
        if "_error" in leases:
            kea["leases_error"] = leases["_error"]
        else:
            kea["leases"] = [
                {"address": r.get("address", ""), "state": r.get("state", "0")}
                for r in _rows(leases)
            ]
        result["kea"] = kea


def _collect_dnsmasq(client, result):
    ranges = _try(client, "dnsmasq/settings/search_range")
    if "_error" in ranges:
        result["dnsmasq"] = {"_error": ranges["_error"], "_code": ranges.get("_code")}
    else:
        leases = _try(client, "dnsmasq/leases/search")
        dnsmasq = {
            "ranges": [
                {"interface": r.get("interface", ""),
                 "start_addr": r.get("start_addr", ""),
                 "end_addr": r.get("end_addr", ""),
                 "description": r.get("description", "")}
                for r in _rows(ranges)
            ],
        }
        if "_error" in leases:
            dnsmasq["leases_error"] = leases["_error"]
        else:
            dnsmasq["leases"] = [{"address": r.get("address", "")}
                                 for r in _rows(leases)]
        result["dnsmasq"] = dnsmasq


# --- Package audit --------------------------------------------------------
def _cache_dir():
    base = os.environ.get("OMD_ROOT")
    if base:
        path = os.path.join(base, "tmp", "check_mk", "agent_opnsense")
    else:
        path = os.path.join(tempfile.gettempdir(), "agent_opnsense")
    os.makedirs(path, exist_ok=True)
    return path


def _load_json(path):
    try:
        with open(path, encoding="utf-8") as fh:
            return json.load(fh)
    except (OSError, ValueError):
        return {}


def _save_json(path, data):
    tmp = path + ".tmp"
    with open(tmp, "w", encoding="utf-8") as fh:
        json.dump(data, fh)
    os.replace(tmp, path)


def _audit_log_done(status):
    """Return the audit log if upgradestatus shows a finished audit run."""
    if not isinstance(status, dict):
        return None
    log = status.get("log") or ""
    if status.get("status") != "done" or "AUDIT SECURITY" not in log:
        return None
    # The log may contain previous actions; keep only the last audit run.
    idx = log.rfind("***GOT REQUEST TO AUDIT SECURITY***")
    return log[idx:] if idx >= 0 else log


def _cache_path(hostname, kind):
    safe = re.sub(r"[^A-Za-z0-9_.-]", "_", hostname)
    return os.path.join(_cache_dir(), "%s.%s.json" % (safe, kind))


# A pending audit older than this is considered stuck and retriggered.
AUDIT_STALE_S = 900


def _audit_running(hostname):
    """True while an audit started by us has not been picked up yet."""
    pending_since = _load_json(_cache_path(hostname, "audit")).get("pending_since")
    return bool(pending_since) and time.time() - pending_since <= AUDIT_STALE_S


# --- Firmware / updates ---------------------------------------------------
# Minimum gap between two triggered checks when OPNsense still reports no
# result afterwards (e.g. mirrors unreachable), to not probe on every run.
FIRMWARE_RETRY_S = 300


def _no_check_result(firmware):
    """True if OPNsense has no update check result (/tmp/pkg_upgrade.json).

    Status "none" alone is ambiguous: OPNsense also reports it when a check
    result exists but no updates are available. Only without a check result
    the check fields (connection, last_check) are missing.
    """
    return (firmware.get("status") == "none"
            and "connection" not in firmware
            and "last_check" not in firmware)


def collect_firmware(client, hostname, interval_min, audit_running):
    """Read the firmware status; trigger an update check only when due.

    GET core/firmware/status only returns the result of the last check
    (/tmp/pkg_upgrade.json on OPNsense). POST additionally runs a synchronous
    "firmware probe" first, which contacts the package mirrors. The POST is
    sent at most every interval_min minutes, or right away if OPNsense has
    no check result (e.g. after a reboot).
    """
    path = _cache_path(hostname, "firmware")
    cache = _load_json(path)
    now = time.time()
    last_probe = cache.get("last_probe", 0)
    meta = {"interval": interval_min * 60, "probed": False}

    def probe():
        cache["last_probe"] = now  # also on errors: do not hammer the API
        try:
            result = client.call("core/firmware/status", method="POST")
            cache.pop("error", None)
        except (HTTPError, URLError, ValueError, OSError) as exc:
            result = {"_error": str(exc)}
            cache["error"] = str(exc)
        try:
            _save_json(path, cache)
        except OSError as exc:
            meta["cache_error"] = str(exc)
        meta["probed"] = True
        return result

    due = interval_min > 0 and now - last_probe >= interval_min * 60
    firmware = None
    if due and not audit_running:
        firmware = probe()
    if firmware is None or "_error" in firmware:
        # Not due, deferred, or the probe itself failed: read cached status.
        try:
            firmware = client.call("core/firmware/status")
        except (HTTPError, URLError, ValueError, OSError) as exc:
            return {"_error": str(exc)}
        if (_no_check_result(firmware) and interval_min > 0
                and not meta["probed"]):
            if audit_running:
                meta["deferred"] = "package audit running"
            elif now - last_probe >= FIRMWARE_RETRY_S:
                probed = probe()
                if "_error" not in probed:
                    firmware = probed
    if due and audit_running:
        meta["deferred"] = "package audit running"
    if meta["probed"] and _no_check_result(firmware):
        # launcher.sh uses "flock -n": if another firmware action holds the
        # lock (GUI, cron, audit), the check is silently skipped.
        meta["probe_no_result"] = True
    meta["retry_s"] = FIRMWARE_RETRY_S
    if cache.get("last_probe"):
        meta["last_probe"] = cache["last_probe"]
    if cache.get("error"):
        meta["probe_error"] = cache["error"]
    firmware["_agent"] = meta
    return firmware


def collect_audit(client, hostname, interval_min, wait_s=30):
    """Run "pkg audit" on the firewall at most every interval_min minutes.

    The audit is asynchronous on OPNsense: POST core/firmware/audit starts
    it, GET core/firmware/upgradestatus reports progress and the log. A run
    that does not finish within wait_s is picked up by a single status poll
    on each following agent call (no waiting there).
    """
    if interval_min <= 0:
        return {"enabled": False}
    path = _cache_path(hostname, "audit")
    cache = _load_json(path)
    now = time.time()

    pending_since = cache.get("pending_since")
    due = now - cache.get("last_run", 0) >= interval_min * 60
    # Stuck/foreign runs: give up waiting after 15 minutes and retrigger.
    if pending_since and now - pending_since > AUDIT_STALE_S:
        pending_since = None

    started_now = False
    if due and not pending_since:
        started = _try(client, "core/firmware/audit", method="POST")
        if "_error" in started:
            cache["error"] = started["_error"]
            cache["last_run"] = now  # do not hammer the API on errors
            _save_json(path, cache)
            return dict(cache, enabled=True, interval=interval_min * 60)
        pending_since = now
        started_now = True
        cache["pending_since"] = now
        _save_json(path, cache)

    if pending_since:
        # Only the run that started the audit waits; later runs poll once.
        deadline = time.time() + (wait_s if started_now else 0)
        while True:
            status = _try(client, "core/firmware/upgradestatus")
            log = _audit_log_done(status)
            if log is not None:
                cache = {"last_run": time.time(), "log": log}
                _save_json(path, cache)
                break
            if time.time() >= deadline:
                break
            time.sleep(2)

    out = dict(cache, enabled=True, interval=interval_min * 60)
    out["pending"] = bool(cache.get("pending_since"))
    return out


def main(argv=None):
    args = parse_args(argv if argv is not None else sys.argv[1:])
    ctx = make_context(args.no_cert_check)
    client = OPNsenseClient(args.hostname, args.port, args.api_key,
                            args.api_secret, ctx, args.timeout)

    # --- Firmware / updates (update check throttled, see collect_firmware) ---
    try:
        audit_running = args.audit_interval > 0 and _audit_running(args.hostname)
        firmware = collect_firmware(client, args.hostname,
                                    args.firmware_check_interval, audit_running)
    except OSError as exc:
        firmware = {"_error": "cache: %s" % exc}
    emit("opnsense_firmware", firmware)

    # --- Services (per-service discovery) ---
    services = {}
    try:
        services = client.call("core/service/search")
    except (HTTPError, URLError, ValueError) as exc:
        services = {"_error": str(exc)}
    emit("opnsense_services", services)

    # --- System status + diagnostics gauges ---
    system = {}
    for key, path, method in (
        ("status", "core/system/status", "GET"),
        ("time", "diagnostics/system/system_time", "GET"),
        ("resources", "diagnostics/system/system_resources", "GET"),
        ("disk", "diagnostics/system/system_disk", "GET"),
        ("swap", "diagnostics/system/system_swap", "GET"),
        ("temperature", "diagnostics/system/system_temperature", "GET"),
    ):
        try:
            system[key] = client.call(path, method=method)
        except (HTTPError, URLError, ValueError) as exc:
            system[key] = {"_error": str(exc)}
    emit("opnsense_system", system)

    # --- SMART disk health (requires os-smart plugin) ---
    smart = {"installed": False, "devices": []}
    try:
        roster = client.call("smart/service/list", method="POST")
        devices = []
        for dev in roster.get("devices", []):
            if not isinstance(dev, str) or not dev:
                continue
            try:
                info = client.call(
                    "smart/service/info",
                    method="POST",
                    form={"device": dev, "type": "a", "json": "1"},
                )
                state = info.get("output") if isinstance(info, dict) else None
                devices.append({"device": dev, "state": state})
            except (HTTPError, URLError, ValueError) as exc:
                devices.append({"device": dev, "state": None,
                                "_error": str(exc)})
        smart = {"installed": True, "devices": devices}
    except (HTTPError, URLError, ValueError) as exc:
        # If the smart module is absent we get a 404; treat as not installed.
        smart = {"installed": False, "devices": [], "_error": str(exc)}
    emit("opnsense_smart", smart)

    # --- Gateways (dpinger status) ---
    emit("opnsense_gateways", _try(client, "routes/gateway/status"))

    # --- WireGuard peers ---
    emit("opnsense_wireguard", _try(client, "wireguard/service/show"))

    # --- DHCP pool usage (Kea / Dnsmasq) ---
    emit("opnsense_dhcp", collect_dhcp(client, services))

    # --- Package audit (pkg audit, cached) ---
    try:
        audit = collect_audit(client, args.hostname, args.audit_interval)
    except OSError as exc:
        audit = {"enabled": True, "_error": "cache: %s" % exc}
    emit("opnsense_audit", audit)
    return 0


if __name__ == "__main__":
    sys.exit(main())
