#!/usr/bin/python3
# Nagios/Icinga plugin to check a Home Assistant instance via its REST API.
#
# Copyright (c) 2026 Thomas Wagner
# SPDX-License-Identifier: GPL-2.0-or-later

import argparse
import fnmatch
import json
import os
import re
import socket
import ssl
import sys
import time
import urllib.error
import urllib.request
from datetime import datetime, timezone

OK = 0
WARNING = 1
CRITICAL = 2
UNKNOWN = 3

STATE_TEXT = {OK: "OK", WARNING: "WARNING", CRITICAL: "CRITICAL", UNKNOWN: "UNKNOWN"}

VERSION = "0.2.1"
DEFAULT_PORT = 8123
DEFAULT_TIMEOUT = 10
MAX_LISTED = 5          # entities named in the output line
MAX_VERBOSE = 40        # ... with -v
MAX_PERFDATA = 20       # per-entity values in the performance data of battery

# config entry states that mean the integration is not working (everything but "loaded")
ENTRY_CRITICAL = {"setup_error", "migration_error", "failed_unload"}
ENTRY_WARNING = {"setup_retry", "not_loaded", "setup_in_progress"}


class PluginError(Exception):
    def __init__(self, state, message):
        super().__init__(message)
        self.state = state
        self.message = message


class Range:
    """Threshold range as defined by the monitoring plugins guidelines."""

    def __init__(self, start, end, inside):
        self.start = start
        self.end = end
        self.inside = inside
        self.spec = self._normalized()

    def _normalized(self):
        """Threshold as perfdata carries it: graphers want a plain number, so one-sided ranges become their bound."""
        if not self.inside and self.start == float("-inf") and self.end == float("inf"):
            return ""
        if not self.inside and self.end == float("inf"):
            return format_number(self.start)
        if not self.inside and self.start in (0, float("-inf")) and self.end != float("inf"):
            return format_number(self.end)
        if self.start == 0 and self.end != float("inf"):
            body = format_number(self.end)
        else:
            low = "~" if self.start == float("-inf") else format_number(self.start)
            high = "" if self.end == float("inf") else format_number(self.end)
            body = "%s:%s" % (low, high)
        return ("@" if self.inside else "") + body

    @classmethod
    def parse(cls, spec, parse_value=float):
        raw = spec
        inside = spec.startswith("@")
        if inside:
            spec = spec[1:]

        if ":" in spec:
            low, high = spec.split(":", 1)
        else:
            low, high = "0", spec

        try:
            start = float("-inf") if low in ("~", "") else parse_value(low)
            end = float("inf") if high == "" else parse_value(high)
        except ValueError:
            raise PluginError(UNKNOWN, "invalid threshold %r" % raw)

        if start > end:
            raise PluginError(UNKNOWN, "invalid threshold %r: start is above end" % raw)

        return cls(start, end, inside)

    def breached(self, value):
        within = self.start <= value <= self.end
        return within if self.inside else not within


def format_number(value):
    if isinstance(value, int) or float(value).is_integer():
        return "%d" % value
    return ("%.3f" % value).rstrip("0").rstrip(".")


def perfdata(label, value, uom="", warn=None, crit=None, minimum=None, maximum=None):
    fields = [
        warn.spec if warn else "",
        crit.spec if crit else "",
        "" if minimum is None else format_number(minimum),
        "" if maximum is None else format_number(maximum),
    ]
    while fields and fields[-1] == "":
        fields.pop()
    out = "%s=%s%s" % (label, format_number(value), uom)
    if fields:
        out += ";" + ";".join(fields)
    return out


def label_of(entity_id):
    """Entity id as a perfdata label (no quotes or equal signs needed)."""
    return re.sub(r"[^A-Za-z0-9_.-]", "_", entity_id)


def number(text):
    """The state as a float, or None if it is not a number."""
    try:
        value = float(text)
    except (TypeError, ValueError):
        return None
    return value if value == value and abs(value) != float("inf") else None


def name_of(state):
    return state.get("attributes", {}).get("friendly_name") or state["entity_id"]


def read_token(args):
    path = args.token_file or os.environ.get("HOMEASSISTANT_TOKEN_FILE")
    if path:
        try:
            with open(os.path.expanduser(path), "r") as handle:
                return handle.read().strip()
        except OSError as err:
            raise PluginError(UNKNOWN, "cannot read token file: %s" % err)
    token = os.environ.get("HOMEASSISTANT_TOKEN")
    if token:
        return token.strip()
    raise PluginError(UNKNOWN, "no access token given, use -f or $HOMEASSISTANT_TOKEN_FILE")


def api_get(args, path, token):
    """(decoded JSON, seconds) of GET /api<path>."""
    url = "%s://%s:%d/api%s" % ("https" if args.ssl else "http", args.hostname, args.port, path)
    req = urllib.request.Request(url, headers={"Accept": "application/json",
                                               "Authorization": "Bearer " + token})
    context = None
    if args.ssl:
        context = ssl.create_default_context()
        if args.insecure:
            context.check_hostname = False
            context.verify_mode = ssl.CERT_NONE
    started = time.monotonic()
    try:
        with urllib.request.urlopen(req, timeout=args.timeout, context=context) as response:
            body = response.read()
        return json.loads(body.decode("utf-8")), time.monotonic() - started
    except urllib.error.HTTPError as err:
        if err.code in (401, 403):
            raise PluginError(UNKNOWN, "access token rejected for /api%s (HTTP %d)" % (path, err.code))
        if err.code == 404:
            raise PluginError(UNKNOWN, "/api%s not found (HTTP 404)" % path)
        if err.code >= 500:
            raise PluginError(CRITICAL, "server error on /api%s (HTTP %d)" % (path, err.code))
        raise PluginError(UNKNOWN, "unexpected HTTP %d on /api%s" % (err.code, path))
    except urllib.error.URLError as err:
        raise PluginError(CRITICAL, "cannot reach %s: %s" % (url, err.reason))
    except socket.timeout:
        raise PluginError(CRITICAL, "timeout after %gs while reading %s" % (args.timeout, url))
    except (UnicodeDecodeError, ValueError):
        raise PluginError(UNKNOWN, "no valid JSON returned by /api%s" % path)


def excluded(patterns, *names):
    return any(fnmatch.fnmatch(name, pattern) for pattern in patterns for name in names)


def threshold_state(args, value, default_warn_above_zero=False):
    """CRITICAL/WARNING by the -c/-w ranges; with no range at all, optionally WARNING for any value above 0."""
    if args.critical and args.critical.breached(value):
        return CRITICAL
    if args.warning and args.warning.breached(value):
        return WARNING
    if default_warn_above_zero and not args.warning and not args.critical and value > 0:
        return WARNING
    return OK


def listing(items, args):
    limit = MAX_VERBOSE if args.verbose else MAX_LISTED
    text = ", ".join(items[:limit])
    if len(items) > limit:
        text += ", and %d more" % (len(items) - limit)
    return text


def check_health(args):
    token = read_token(args)
    answer, elapsed = api_get(args, "/", token)
    if answer.get("message") != "API running.":
        raise PluginError(CRITICAL, "unexpected answer from /api/: %r" % (answer,))
    config, more = api_get(args, "/config", token)
    elapsed += more

    version = config["version"]
    run_state = config.get("state", "RUNNING")
    components = len(config.get("components", []))
    notes = [name for name in ("safe_mode", "recovery_mode") if config.get(name)]

    state = OK
    if run_state != "RUNNING":
        state = CRITICAL
    elif notes:
        state = WARNING
    if state == OK:
        if args.critical and args.critical.breached(elapsed):
            state = CRITICAL
        elif args.warning and args.warning.breached(elapsed):
            state = WARNING

    message = "version %s, %s, %d components, answered in %.3fs" % (version, run_state, components, elapsed)
    if notes:
        message += ", " + " and ".join(note.replace("_", " ") for note in notes) + " is on"
    perf = [perfdata("time", round(elapsed, 3), "s", args.warning, args.critical, 0),
            perfdata("components", components, "", None, None, 0)]
    return state, message, perf


def check_updates(args):
    token = read_token(args)
    states, _ = api_get(args, "/states", token)
    updates = [s for s in states if s["entity_id"].startswith("update.")
               and not excluded(args.exclude, s["entity_id"], name_of(s))]
    pending = [s for s in updates if s["state"] == "on"]

    def describe(item):
        attrs = item.get("attributes", {})
        name = name_of(item)
        old, new = attrs.get("installed_version"), attrs.get("latest_version")
        return "%s %s -> %s" % (name, old, new) if old and new else name

    state = threshold_state(args, len(pending), default_warn_above_zero=True)
    if pending:
        message = "%d of %d updates available: %s" % (len(pending), len(updates),
                                                      listing([describe(s) for s in pending], args))
    else:
        message = "no update pending (%d update entities)" % len(updates)
    perf = [perfdata("pending", len(pending), "", args.warning, args.critical, 0, len(updates)),
            perfdata("entities", len(updates), "", None, None, 0)]
    return state, message, perf


def check_unavailable(args):
    token = read_token(args)
    states, _ = api_get(args, "/states", token)
    wanted = {"unavailable"} | ({"unknown"} if args.unknown else set())
    considered = [s for s in states if not excluded(args.exclude, s["entity_id"], name_of(s))]
    gone = sorted(s["entity_id"] for s in considered if s["state"] in wanted)

    state = threshold_state(args, len(gone))
    word = "unavailable or unknown" if args.unknown else "unavailable"
    message = "%d of %d entities %s" % (len(gone), len(considered), word)
    if gone:
        message += ": " + listing(gone, args)
    perf = [perfdata("unavailable", len(gone), "", args.warning, args.critical, 0, len(considered)),
            perfdata("entities", len(considered), "", None, None, 0)]
    return state, message, perf


def check_battery(args):
    token = read_token(args)
    states, _ = api_get(args, "/states", token)
    levels, low_flags, offline = [], [], 0
    for item in states:
        if item.get("attributes", {}).get("device_class") != "battery":
            continue
        if excluded(args.exclude, item["entity_id"], name_of(item)):
            continue
        if item["state"] in ("unavailable", "unknown"):
            offline += 1
        elif item["entity_id"].startswith("binary_sensor."):
            if item["state"] == "on":  # on means low for a battery binary sensor
                low_flags.append(item)
        else:
            value = number(item["state"])
            if value is not None:
                levels.append((value, item))

    warn = args.warning or Range.parse("20:")
    crit = args.critical or Range.parse("10:")
    state, bad = OK, []
    for value, item in sorted(levels, key=lambda pair: pair[0]):
        if crit.breached(value):
            state = CRITICAL
            bad.append("%s %s%%" % (name_of(item), format_number(value)))
        elif warn.breached(value):
            state = max(state, WARNING)
            bad.append("%s %s%%" % (name_of(item), format_number(value)))
    for item in low_flags:
        state = max(state, WARNING)
        bad.append("%s is low" % name_of(item))

    total = len(levels) + len(low_flags)
    if bad:
        message = "%d of %d batteries low: %s" % (len(bad), total, listing(bad, args))
    elif levels:
        message = "%d batteries ok, lowest %s%%" % (total, format_number(min(v for v, _ in levels)))
    else:
        message = "no battery entity with a level found"
    if offline:
        message += " (%d unavailable)" % offline
    perf = [perfdata(label_of(item["entity_id"]), value, "%", warn, crit, 0, 100)
            for value, item in sorted(levels, key=lambda pair: pair[0])[:MAX_PERFDATA]]
    return state, message, perf


def check_integrations(args):
    token = read_token(args)
    entries, _ = api_get(args, "/config/config_entries/entry", token)
    considered, critical, warning = 0, [], []
    for entry in entries:
        if entry.get("disabled_by"):
            continue
        if excluded(args.exclude, entry.get("domain", ""), entry.get("title", "")):
            continue
        considered += 1
        entry_state = entry.get("state", "")
        if entry_state == "loaded":
            continue
        text = "%s (%s): %s" % (entry.get("domain"), entry.get("title"), entry_state)
        if entry.get("reason"):
            text += ", " + str(entry["reason"])
        if entry_state in ENTRY_CRITICAL:
            critical.append(text)
        else:
            warning.append(text)

    state = CRITICAL if critical else WARNING if warning else OK
    problems = critical + warning
    if problems:
        message = "%d of %d integrations not loaded: %s" % (len(problems), considered, listing(problems, args))
    else:
        message = "all %d integrations loaded" % considered
    perf = [perfdata("failed", len(critical), "", None, None, 0, considered),
            perfdata("not_loaded", len(warning), "", None, None, 0, considered),
            perfdata("entries", considered, "", None, None, 0)]
    return state, message, perf


def state_matches(patterns, text, use_regex):
    if not use_regex:
        return text in patterns
    try:
        return any(re.fullmatch(pattern, text) for pattern in patterns)
    except re.error as err:
        raise PluginError(UNKNOWN, "invalid regular expression: %s" % err)


def timestamp_age(text):
    """Seconds since a timestamp state: epoch seconds, or an ISO 8601 date and time."""
    value = number(text)
    if value is not None:
        return time.time() - value
    try:
        moment = datetime.fromisoformat(str(text).replace("Z", "+00:00"))
    except ValueError:
        return None
    if moment.tzinfo is None:
        moment = moment.astimezone()  # no zone given: local time, as Home Assistant shows it
    return (datetime.now(timezone.utc) - moment).total_seconds()


def check_entity(args):
    if not args.entity:
        raise PluginError(UNKNOWN, "entity needs -e ENTITY_ID")
    token = read_token(args)
    try:
        item, _ = api_get(args, "/states/" + urllib.request.quote(args.entity, safe="._"), token)
    except PluginError as err:
        if "HTTP 404" in err.message:
            raise PluginError(UNKNOWN, "entity %s does not exist" % args.entity)
        raise

    value_text = str(item.get("state"))
    attrs = item.get("attributes", {})
    unit = attrs.get("unit_of_measurement") or ""
    perf_unit = unit if unit in ("%", "s", "B") else ""
    name = name_of(item)
    label = label_of(args.entity)

    if value_text in ("unavailable", "unknown"):
        return CRITICAL if args.unavailable_critical else WARNING, "%s is %s" % (name, value_text), []

    if args.timestamp:
        age = timestamp_age(value_text)
        if age is None:
            raise PluginError(UNKNOWN, "%s is %r, not a timestamp" % (name, value_text))
        state = threshold_state(args, age)
        message = "%s was last set %d s ago" % (name, round(age))
        return state, message, [perfdata(label + "_age", round(age, 1), "s", args.warning, args.critical, 0)]

    if args.expect or args.not_expect:
        state, notes = OK, []
        if args.expect and not state_matches(args.expect, value_text, args.regex):
            state = CRITICAL
            notes.append("expected %s" % " or ".join(args.expect))
        if args.not_expect and state_matches(args.not_expect, value_text, args.regex):
            state = CRITICAL
            notes.append("not expected %s" % " or ".join(args.not_expect))
        message = "%s is %s" % (name, value_text)
        if notes:
            message += ", " + ", ".join(notes)
        value = number(value_text)
        return state, message, [] if value is None else [perfdata(label, value, perf_unit)]

    value = number(value_text)
    if value is None:
        if args.warning or args.critical:
            raise PluginError(UNKNOWN, "%s is %r, not a number, thresholds do not apply" % (name, value_text))
        return OK, "%s is %s" % (name, value_text), []

    state = threshold_state(args, value)
    message = "%s is %s%s" % (name, format_number(value), (" " + unit) if unit else "")
    return state, message, [perfdata(label, value, perf_unit, args.warning, args.critical)]


MODES = {
    "health": (check_health, "check that Home Assistant answers and is running", float),
    "updates": (check_updates, "report pending updates of Home Assistant, add-ons and devices", float),
    "unavailable": (check_unavailable, "count entities that are unavailable", float),
    "battery": (check_battery, "check the levels of all battery entities", float),
    "integrations": (check_integrations, "check that every integration is loaded", float),
    "entity": (check_entity, "check the value, state or age of one entity", float),
}


class ArgumentParser(argparse.ArgumentParser):
    """argparse exits 2 on a usage error, which Nagios reads as CRITICAL; exit UNKNOWN instead."""

    def error(self, message):
        self.print_usage(sys.stderr)
        sys.stderr.write("%s: error: %s\n" % (self.prog, message))
        sys.exit(UNKNOWN)


def build_parser():
    parser = ArgumentParser(
        prog="check_homeassistant",
        description="Nagios/Icinga plugin to check a Home Assistant instance via its REST API.",
    )
    parser.add_argument("-V", "--version", action="version", version="check_homeassistant %s" % VERSION)

    connection = ArgumentParser(add_help=False)
    connection.add_argument("-H", "--hostname", required=True, help="host name or address of Home Assistant")
    connection.add_argument("-p", "--port", type=int, default=DEFAULT_PORT,
                            help="port of Home Assistant (default: %d)" % DEFAULT_PORT)
    connection.add_argument("-S", "--ssl", action="store_true", help="use HTTPS instead of HTTP")
    connection.add_argument("-k", "--insecure", action="store_true", help="do not verify the TLS certificate")
    connection.add_argument("-t", "--timeout", type=float, default=DEFAULT_TIMEOUT,
                            help="timeout in seconds (default: %d)" % DEFAULT_TIMEOUT)
    connection.add_argument("-f", "--token-file", help="file holding the long-lived access token")

    check = ArgumentParser(add_help=False)
    check.add_argument("-w", "--warning", help="warning threshold as a range")
    check.add_argument("-c", "--critical", help="critical threshold as a range")
    check.add_argument("-x", "--exclude", action="append", default=[], metavar="PATTERN",
                       help="skip entities whose id or name matches this shell pattern (integrations: "
                            "domain or title); can be repeated")
    check.add_argument("-v", "--verbose", action="store_true", help="list more entities in the output")

    subparsers = parser.add_subparsers(dest="mode", required=True, metavar="MODE")
    for name, (_, description, _) in sorted(MODES.items()):
        sub = subparsers.add_parser(name, parents=[connection, check], help=description,
                                    description=description)
        if name == "unavailable":
            sub.add_argument("--unknown", action="store_true", help="count entities in state unknown too")
        if name == "entity":
            sub.add_argument("-e", "--entity", help="entity id, e.g. sensor.system_monitor_disk_free")
            sub.add_argument("--expect", action="append", default=[], metavar="STATE",
                             help="CRITICAL unless the state is this text; can be repeated")
            sub.add_argument("--not-expect", action="append", default=[], metavar="STATE",
                             help="CRITICAL if the state is this text; can be repeated")
            sub.add_argument("-R", "--regex", action="store_true",
                             help="--expect and --not-expect are regular expressions that must match the "
                                  "whole state")
            sub.add_argument("--timestamp", action="store_true",
                             help="the state is a timestamp (epoch seconds or ISO 8601); -w and -c are "
                                  "ranges of its age in seconds")
            sub.add_argument("--unavailable-critical", action="store_true",
                             help="CRITICAL instead of WARNING if the entity is unavailable or unknown")
    return parser


def main():
    args = build_parser().parse_args()
    try:
        handler, _, parse_value = MODES[args.mode]
        args.warning = Range.parse(args.warning, parse_value) if args.warning else None
        args.critical = Range.parse(args.critical, parse_value) if args.critical else None
        state, message, perf = handler(args)
    except (KeyError, TypeError, ValueError, IndexError, AttributeError) as err:
        print("HOMEASSISTANT %s UNKNOWN - unexpected answer from the server: %r" % (args.mode.upper(), err))
        return UNKNOWN
    except PluginError as err:
        print("HOMEASSISTANT %s %s - %s" % (args.mode.upper(), STATE_TEXT[err.state], err.message))
        return err.state

    output = "HOMEASSISTANT %s %s - %s" % (args.mode.upper(), STATE_TEXT[state], message)
    if perf:
        output += " | " + " ".join(perf)
    print(output)
    return state


if __name__ == "__main__":
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        sys.exit(UNKNOWN)
