#!/usr/bin/env python3
"""Checkmk special agent for Jamf Pro.

Collects Apple Business Manager certificate and token state from a Jamf Pro
tenant through the Jamf Pro API, using OAuth2 client credentials.

Author:   Sher Zaman
Company:  FirmaTRUST | Managed IT and Cybersecurity
Email:    sher[at]sherz[dot]dev
Website:  https://sherz.dev
LinkedIn: https://www.linkedin.com/in/sher-zaman-95b008114/
Repo:     https://github.com/sher-zaman/Checkmk

License: GPL-2.0-only
"""

import argparse
import json
import ssl
import sys
from pathlib import Path
import urllib.error
import urllib.parse
import urllib.request

# The client secret is passed as a password-store reference rather than plain
# text, so the credential never appears in the process table. Resolving that
# reference needs Checkmk's password store, which is present when the agent is
# invoked by the Checkmk core but not when it is run by hand. Manual runs use
# --secret or stdin instead.
#
# Both resolve paths are imported here and neither is selected at import time.
# Checkmk 2.5 and later ship a dedicated password store API, and earlier
# versions expose the same on-disk store through an internal module. On some
# builds the newer module imports cleanly but exposes no usable lookup, so
# choosing a path on import alone makes the fallback unreachable. The resolver
# below tries each candidate in turn and only gives up once every one has
# failed.
try:  # Checkmk 2.5+ dedicated API
    from cmk.password_store import v1_unstable as _pwstore_v1
except ImportError:  # pragma: no cover - depends on execution environment
    _pwstore_v1 = None

try:  # Checkmk 2.3 and 2.4, and 2.5 as a fallback
    from cmk.utils import password_store as _pwstore_legacy
except ImportError:  # pragma: no cover
    _pwstore_legacy = None

# Lookup callables, in the order they are tried. Names differ between builds.
_PWSTORE_LOOKUP_NAMES = ("lookup", "resolve", "reveal", "lookup_secret", "get")

TOKEN_PATH = "/api/oauth/token"

SECTIONS = {
    "jamf_pro_info": None,
    "jamf_pro_ade": None,
    "jamf_pro_vpp": None,
    "jamf_pro_notifications": None,
}


def _call_lookup(func, store_file, secret_id):
    """Call a password store lookup, tolerating the two known signatures."""
    try:
        result = func(Path(store_file), secret_id)
    except TypeError:
        result = func(secret_id)
    # Some variants return a wrapper exposing .reveal()
    revealer = getattr(result, "reveal", None)
    return revealer() if callable(revealer) else result


def _resolve_from_store(reference):
    """Resolve a "<id>:<store file>" reference into the real client secret.

    Every available path is tried in turn: the Checkmk 2.5+ API first, then the
    older internal module. The resolved value is returned to the caller and held
    only in this process's memory; it is never logged, printed, or written to
    disk. If every path fails, the names each module does expose are reported so
    the cause is visible rather than guessed at.
    """
    if ":" not in reference:
        sys.stderr.write("Malformed --secret-id, expected <id>:<store file>\n")
        sys.exit(1)
    secret_id, store_file = reference.split(":", 1)

    attempts = []
    for label, module in (("cmk.password_store.v1_unstable", _pwstore_v1),
                          ("cmk.utils.password_store", _pwstore_legacy)):
        if module is None:
            attempts.append("%s: not importable" % label)
            continue

        found = False
        for name in _PWSTORE_LOOKUP_NAMES:
            func = getattr(module, name, None)
            if not callable(func):
                continue
            found = True
            try:
                value = _call_lookup(func, store_file, secret_id)
            except Exception as exc:  # pylint: disable=broad-except
                # Only the failure reason is reported, never the credential.
                attempts.append("%s.%s raised %s: %s"
                                % (label, name, type(exc).__name__, exc))
                continue
            if value:
                return value
            attempts.append("%s.%s returned nothing" % (label, name))

        if not found:
            public = [n for n in dir(module) if not n.startswith("_")]
            attempts.append("%s exposes no known lookup, available names: %s"
                            % (label, ", ".join(public) or "none"))

    sys.stderr.write(
        "Could not resolve the client secret from the Checkmk password store. "
        "Use --secret for manual runs.\n"
    )
    for line in attempts:
        sys.stderr.write("  %s\n" % line)
    sys.exit(1)


def resolve_secret(args):
    """Return the plaintext client secret from whichever source was supplied.

    Preference order: an explicit --secret (manual runs), then a --secret-id
    password store reference (how the Checkmk core invokes this agent), then
    stdin (manual runs without shell history exposure).
    """
    if args.secret is not None:
        return args.secret

    if args.secret_id:
        try:
            return _resolve_from_store(args.secret_id)
        except SystemExit:
            raise
        except Exception as exc:  # pylint: disable=broad-except
            # Only the failure reason is reported, never the credential.
            sys.stderr.write("Failed to resolve client secret from store: %s\n" % exc)
            sys.exit(1)

    if not sys.stdin.isatty():
        piped = sys.stdin.read().strip()
        if piped:
            return piped

    sys.stderr.write("No client secret supplied. Use --secret, --secret-id or stdin.\n")
    sys.exit(1)


class JamfError(Exception):
    pass


class JamfClient:
    def __init__(self, base_url, client_id, secret, timeout, verify_ssl):
        self.base = base_url.rstrip("/")
        if self.base.endswith("/api"):
            self.base = self.base[:-4]
        self.client_id = client_id
        self.secret = secret
        self.timeout = timeout
        if verify_ssl:
            ctx = ssl.create_default_context()
        else:
            ctx = ssl.create_default_context()
            ctx.check_hostname = False
            ctx.verify_mode = ssl.CERT_NONE
        self.opener = urllib.request.build_opener(urllib.request.HTTPSHandler(context=ctx))
        self.token = None

    def authenticate(self):
        body = urllib.parse.urlencode({
            "grant_type": "client_credentials",
            "client_id": self.client_id,
            "client_secret": self.secret,
        }).encode()
        req = urllib.request.Request(self.base + TOKEN_PATH, data=body, method="POST")
        req.add_header("Content-Type", "application/x-www-form-urlencoded")
        req.add_header("Accept", "application/json")
        try:
            with self.opener.open(req, timeout=self.timeout) as resp:
                payload = json.loads(resp.read().decode("utf-8"))
        except urllib.error.HTTPError as exc:
            raise JamfError("authentication failed: HTTP %s" % exc.code) from exc
        except Exception as exc:  # noqa: BLE001
            raise JamfError("authentication failed: %s" % exc) from exc

        self.token = payload.get("access_token")
        if not self.token:
            raise JamfError("authentication succeeded but no access token was returned")

    def get(self, path):
        """GET a path. Returns parsed JSON, or None when the call fails."""
        req = urllib.request.Request(self.base + path, method="GET")
        req.add_header("Authorization", "Bearer " + self.token)
        req.add_header("Accept", "application/json")
        try:
            with self.opener.open(req, timeout=self.timeout) as resp:
                raw = resp.read().decode("utf-8")
        except Exception as exc:  # noqa: BLE001
            sys.stderr.write("GET %s failed: %s\n" % (path, exc))
            return None
        if not raw.strip():
            return None
        try:
            return json.loads(raw)
        except ValueError:
            sys.stderr.write("GET %s returned non-JSON content\n" % path)
            return None


def collect_info(client):
    info = {}
    version = client.get("/api/v1/jamf-pro-version")
    if isinstance(version, dict):
        info["version"] = version.get("version")
    details = client.get("/api/v2/jamf-pro-information")
    if isinstance(details, dict):
        info["depAccountEnabled"] = details.get("depAccountEnabled")
        info["vppTokenEnabled"] = details.get("vppTokenEnabled")
        info["cloudDeploymentsEnabled"] = details.get("cloudDeploymentsEnabled")
    return info


def collect_ade(client):
    """ADE instances, each with the outcome of its most recent Apple sync."""
    payload = client.get("/api/v1/device-enrollments?page=0&page-size=100")
    if not isinstance(payload, dict):
        return []

    instances = []
    for entry in payload.get("results", []):
        record = {
            "id": str(entry.get("id", "")),
            "name": entry.get("name") or "ADE instance %s" % entry.get("id"),
            "tokenExpirationDate": entry.get("tokenExpirationDate"),
            "serverName": entry.get("serverName"),
        }
        sync = client.get("/api/v1/device-enrollments/%s/syncs/latest" % record["id"])
        if isinstance(sync, dict):
            record["syncStatus"] = sync.get("syncStatus")
            record["syncTime"] = sync.get("syncTime")
        instances.append(record)
    return instances


def collect_vpp(client):
    payload = client.get("/api/v1/volume-purchasing-locations?page=0&page-size=100")
    if not isinstance(payload, dict):
        return []

    locations = []
    for entry in payload.get("results", []):
        locations.append({
            "id": str(entry.get("id", "")),
            "name": entry.get("name") or entry.get("locationName") or "VPP location",
            "tokenExpiration": entry.get("tokenExpiration"),
            "lastSyncTime": entry.get("lastSyncTime"),
            "clientContextMismatch": entry.get("clientContextMismatch"),
            "totalPurchasedLicenses": entry.get("totalPurchasedLicenses"),
            "totalUsedLicenses": entry.get("totalUsedLicenses"),
        })
    return locations


def collect_notifications(client):
    """Jamf's own alert banner feed. Returns a bare list, or an empty list."""
    payload = client.get("/api/v1/notifications")
    if isinstance(payload, list):
        return payload
    if isinstance(payload, dict):
        # Defensive: a future version may wrap the list.
        results = payload.get("results")
        if isinstance(results, list):
            return results
    return []


def emit(name, data):
    print("<<<%s:sep(0)>>>" % name)
    print(json.dumps(data))


def main():
    parser = argparse.ArgumentParser("agent_jamf_pro")
    parser.add_argument("--url", required=True, help="https://TENANT.jamfcloud.com")
    parser.add_argument("--client-id", required=True, help="API client ID")
    parser.add_argument(
        "--secret",
        help="API client secret in plain text. Intended for manual runs only; "
        "the Checkmk core uses --secret-id instead.",
    )
    parser.add_argument(
        "--secret-id",
        help="Password store reference in the form <id>:<store file>. "
        "Resolved inside this process so the secret never reaches argv.",
    )
    parser.add_argument("--timeout", type=int, default=30, help="Per-request timeout")
    parser.add_argument("--no-cert-check", action="store_true",
                        help="Do not verify the TLS certificate")
    args = parser.parse_args()

    client = JamfClient(
        base_url=args.url,
        client_id=args.client_id,
        secret=resolve_secret(args),
        timeout=args.timeout,
        verify_ssl=not args.no_cert_check,
    )

    try:
        client.authenticate()
    except JamfError as exc:
        sys.stderr.write("%s\n" % exc)
        return 1

    emit("jamf_pro_info", collect_info(client))
    emit("jamf_pro_ade", collect_ade(client))
    emit("jamf_pro_vpp", collect_vpp(client))
    emit("jamf_pro_notifications", collect_notifications(client))
    return 0


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