#!/usr/bin/env python3
# check_sauna - monitoring plugin for a sauna temperature / humidity sensor
# that serves its readings as JSON over HTTP(S).
#
# Copyright (c) 2026 DIVELUX Inc. MIT License (see LICENSE).
# https://diveluxsaunahat.com/pages/sauna-tools#check-sauna
#
# Follows the Monitoring Plugins Development Guidelines: exit codes
# OK=0 WARNING=1 CRITICAL=2 UNKNOWN=3, one line of output with performance
# data, Nagios range syntax for -w / -c, and a plugin-wide timeout (-t).
# Python 3.6+ standard library only.

import argparse
import base64
import json
import math
import os
import re
import signal
import socket
import ssl
import sys
import time
import urllib.error
import urllib.request

VERSION = "1.0.0"
PROG = "check_sauna"

OK, WARNING, CRITICAL, UNKNOWN = 0, 1, 2, 3
STATE_NAMES = {OK: "OK", WARNING: "WARNING", CRITICAL: "CRITICAL", UNKNOWN: "UNKNOWN"}
STATE_BY_NAME = {"ok": OK, "warning": WARNING, "critical": CRITICAL, "unknown": UNKNOWN}

MAX_BODY = 1024 * 1024  # a sensor reading is a few hundred bytes; refuse anything over 1 MiB


class PluginError(Exception):
    """Ends the check with the given state and message."""

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


def finish(state, text, perfdata=None, long_lines=None):
    line = "SAUNA %s - %s" % (STATE_NAMES[state], text)
    if perfdata:
        line += " | " + " ".join(perfdata)
    out = [line]
    if long_lines:
        out.extend(long_lines)
    sys.stdout.write("\n".join(out) + "\n")
    sys.stdout.flush()
    sys.exit(state)


# ---------------------------------------------------------------------------
# Threshold ranges, as defined in the Monitoring Plugins Development Guidelines:
#   10      alert if < 0 or > 10
#   10:     alert if < 10
#   ~:10    alert if > 10
#   10:20   alert if < 10 or > 20
#   @10:20  alert if >= 10 and <= 20


class Range(object):
    _num = r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)"

    def __init__(self, text):
        self.text = text
        s = text.strip()
        if not s:
            raise ValueError("empty range")
        self.inside = s.startswith("@")
        if self.inside:
            s = s[1:]
        if not s:
            raise ValueError("empty range")
        if ":" in s:
            lo, hi = s.split(":", 1)
        else:
            lo, hi = "0", s
        if lo == "~":
            self.start = -math.inf
        elif lo == "":
            self.start = 0.0
        elif re.fullmatch(self._num, lo):
            self.start = float(lo)
        else:
            raise ValueError("bad range start %r" % lo)
        if hi == "":
            self.end = math.inf
        elif re.fullmatch(self._num, hi):
            self.end = float(hi)
        else:
            raise ValueError("bad range end %r" % hi)
        if self.start > self.end:
            raise ValueError("range start is greater than its end")

    def alert(self, value):
        """True when value should raise an alert."""
        within = self.start <= value <= self.end
        return within if self.inside else not within

    def __str__(self):
        return self.text


def range_arg(text):
    try:
        return Range(text)
    except ValueError as exc:
        raise argparse.ArgumentTypeError("%s: %s" % (text, exc))


def timeout_arg(text):
    sec, _, state = text.partition(":")
    try:
        sec = int(sec)
    except ValueError:
        raise argparse.ArgumentTypeError("timeout must be whole seconds, e.g. 10 or 10:critical")
    if sec < 1:
        raise argparse.ArgumentTypeError("timeout must be at least 1 second")
    state = state.strip().lower() or "unknown"
    if state not in STATE_BY_NAME or state == "ok":
        raise argparse.ArgumentTypeError("timeout state must be warning, critical or unknown")
    return sec, STATE_BY_NAME[state]


def evaluate(value, warn, crit):
    if crit is not None and crit.alert(value):
        return CRITICAL
    if warn is not None and warn.alert(value):
        return WARNING
    return OK


# ---------------------------------------------------------------------------
# Reading the JSON document


def lookup(doc, path):
    """Find a value by a dotted path: 'temperature', 'sensors.hot_room.c',
    'probes.0.value'. Returns (found, value)."""
    cur = doc
    for part in path.split("."):
        if isinstance(cur, dict):
            if part not in cur:
                return False, None
            cur = cur[part]
        elif isinstance(cur, list):
            if not re.fullmatch(r"-?\d+", part):
                return False, None
            i = int(part)
            if not -len(cur) <= i < len(cur):
                return False, None
            cur = cur[i]
        else:
            return False, None
    return True, cur


def as_number(value, what):
    if isinstance(value, bool) or value is None:
        raise PluginError(UNKNOWN, "%s is not a number: %s" % (what, json.dumps(value)))
    if isinstance(value, (int, float)):
        num = float(value)
    elif isinstance(value, str):
        try:
            num = float(value.strip())
        except ValueError:
            raise PluginError(UNKNOWN, "%s is not a number: %s" % (what, json.dumps(value)))
    else:
        raise PluginError(UNKNOWN, "%s is not a number: %s" % (what, type(value).__name__))
    if math.isnan(num) or math.isinf(num):
        raise PluginError(UNKNOWN, "%s is not a finite number (sensor error?)" % what)
    return num


def parse_unit(text, what):
    u = str(text).strip().upper().replace("\u00b0", "")
    if u in ("C", "CELSIUS"):
        return "C"
    if u in ("F", "FAHRENHEIT"):
        return "F"
    raise PluginError(UNKNOWN, "unknown %s %s (expected C or F)" % (what, json.dumps(text)))


def convert(value, src, dst):
    if src == dst:
        return value
    if src == "C":
        return value * 9.0 / 5.0 + 32.0
    return (value - 32.0) * 5.0 / 9.0


def parse_timestamp(value):
    """Unix seconds (or milliseconds) as a number, or an ISO 8601 string with
    a time zone. Returns Unix seconds."""
    if isinstance(value, (int, float)) and not isinstance(value, bool):
        ts = float(value)
        if ts > 1e11:  # milliseconds
            ts /= 1000.0
        return ts
    if isinstance(value, str):
        s = value.strip()
        if re.fullmatch(r"\d+(\.\d+)?", s):
            return parse_timestamp(float(s))
        from datetime import datetime

        s2 = s[:-1] + "+00:00" if s.endswith("Z") else s
        try:
            dt = datetime.fromisoformat(s2)
        except ValueError:
            dt = None
        if dt is not None and dt.tzinfo is not None:
            return dt.timestamp()
    raise PluginError(
        UNKNOWN,
        "timestamp %s is not Unix seconds or ISO 8601 with a time zone" % json.dumps(value),
    )


# ---------------------------------------------------------------------------
# Fetching


def build_url(args):
    if args.url:
        if not re.match(r"^https?://", args.url, re.I):
            raise PluginError(UNKNOWN, "--url must start with http:// or https://")
        return args.url
    scheme = "https" if args.ssl else "http"
    host = args.hostname
    if ":" in host and not host.startswith("["):
        host = "[%s]" % host  # IPv6 literal
    port = args.port or (443 if args.ssl else 80)
    default = (args.ssl and port == 443) or (not args.ssl and port == 80)
    path = args.uri if args.uri.startswith("/") else "/" + args.uri
    return "%s://%s%s%s" % (scheme, host, "" if default else ":%d" % port, path)


def fetch(url, args, seconds):
    headers = {
        "Accept": "application/json",
        "User-Agent": "%s/%s (monitoring plugin)" % (PROG, VERSION),
    }
    if args.authorization:
        user, sep, pw = args.authorization.partition(":")
        if not sep:
            raise PluginError(UNKNOWN, "-a must be USER:PASSWORD")
        token = base64.b64encode(("%s:%s" % (user, pw)).encode("utf-8")).decode("ascii")
        headers["Authorization"] = "Basic " + token
    for h in args.header or []:
        name, sep, value = h.partition(":")
        if not sep or not name.strip():
            raise PluginError(UNKNOWN, "--header must be 'Name: value'")
        headers[name.strip()] = value.strip()

    req = urllib.request.Request(url, headers=headers)
    ctx = None
    if url.lower().startswith("https://"):
        ctx = ssl.create_default_context(cafile=args.ca_file) if args.ca_file else ssl.create_default_context()
        if args.insecure:
            ctx.check_hostname = False
            ctx.verify_mode = ssl.CERT_NONE
    try:
        resp = urllib.request.urlopen(req, timeout=seconds, context=ctx)
    except urllib.error.HTTPError as exc:
        raise PluginError(CRITICAL, "HTTP %d %s from %s" % (exc.code, exc.reason, url))
    except urllib.error.URLError as exc:
        reason = exc.reason
        if isinstance(reason, socket.timeout) or "timed out" in str(reason):
            raise TimeoutError()
        raise PluginError(CRITICAL, "cannot reach %s: %s" % (url, reason))
    except socket.timeout:
        raise TimeoutError()
    except (ConnectionError, OSError) as exc:
        raise PluginError(CRITICAL, "cannot reach %s: %s" % (url, exc))
    with resp:
        try:
            body = resp.read(MAX_BODY + 1)
        except socket.timeout:
            raise TimeoutError()
    if len(body) > MAX_BODY:
        raise PluginError(UNKNOWN, "response from %s is larger than 1 MiB" % url)
    return body


def read_file(path):
    try:
        if path == "-":
            data = sys.stdin.buffer.read(MAX_BODY + 1)
        else:
            with open(path, "rb") as fh:
                data = fh.read(MAX_BODY + 1)
    except OSError as exc:
        raise PluginError(UNKNOWN, "cannot read %s: %s" % (path, exc.strerror or exc))
    if len(data) > MAX_BODY:
        raise PluginError(UNKNOWN, "%s is larger than 1 MiB" % path)
    return data


# ---------------------------------------------------------------------------


class Parser(argparse.ArgumentParser):
    def error(self, message):
        sys.stdout.write("SAUNA UNKNOWN - %s\nUsage: %s\n" % (message, self.format_usage().strip()))
        sys.exit(UNKNOWN)

    def exit(self, status=0, message=None):
        if message:
            sys.stdout.write(message)
        # --help and --version end with UNKNOWN, like the Monitoring Plugins do
        sys.exit(UNKNOWN)


DESCRIPTION = """\
Checks the temperature (and, if present, the relative humidity) that a sauna
sensor serves as a JSON document over HTTP or HTTPS, against Nagios-style
warning and critical ranges.

The default document is:

  {"temperature": 92.5, "humidity": 11.8, "unit": "C", "timestamp": 1764633600}

Only "temperature" is required. Use --temp-key, --humidity-key, --unit-key and
--timestamp-key for other layouts; a key is a dotted path, e.g.
sensors.hot_room.temp or probes.0.value."""

EPILOG = """\
Range syntax (Monitoring Plugins Development Guidelines):
  10      alert if below 0 or above 10      ~:10    alert if above 10
  10:     alert if below 10                 10:20   alert if outside 10..20
  @10:20  alert if inside 10..20

Examples:
  check_sauna -H 192.168.1.50 -u /sensor.json -w ~:100 -c ~:110
  check_sauna -U https://sauna.example.net/api/state --temp-key hot_room.temp \\
      --unit F -w 150: -c ~:230 -W ~:40 -C ~:60 --max-age 300

Exit codes: 0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN.
This plugin only reports readings. It is not a safety device: the heater's own
thermostat and overheat cut-out protect the room.
https://diveluxsaunahat.com/pages/sauna-tools#check-sauna"""


def make_parser():
    p = Parser(
        prog=PROG,
        description=DESCRIPTION,
        epilog=EPILOG,
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    src = p.add_argument_group("where to read")
    src.add_argument("-H", "--hostname", help="sensor host name or IP address")
    src.add_argument("-p", "--port", type=int, help="TCP port (default 80, or 443 with -S)")
    src.add_argument("-u", "--uri", default="/", help="path of the JSON document (default /)")
    src.add_argument("-S", "--ssl", action="store_true", help="use HTTPS with -H")
    src.add_argument("-U", "--url", help="full URL instead of -H/-p/-u/-S")
    src.add_argument("-f", "--file", help="read the JSON from a file instead ('-' for stdin)")
    src.add_argument("-a", "--authorization", metavar="USER:PASSWORD", help="HTTP basic auth")
    src.add_argument("--header", action="append", metavar="'NAME: VALUE'",
                     help="extra HTTP header, can be repeated (e.g. an API token)")
    src.add_argument("--insecure", action="store_true", help="do not verify the TLS certificate")
    src.add_argument("--ca-file", help="CA bundle to verify the TLS certificate")

    keys = p.add_argument_group("document layout")
    keys.add_argument("--temp-key", default="temperature", help="path of the temperature (default temperature)")
    keys.add_argument("--humidity-key", default="humidity", help="path of the relative humidity in %% (default humidity)")
    keys.add_argument("--unit-key", default="unit", help="path of the temperature unit, C or F (default unit)")
    keys.add_argument("--input-unit", choices=["C", "F", "c", "f"],
                      help="unit of the temperature in the document; overrides --unit-key (default: --unit-key, else C)")
    keys.add_argument("--timestamp-key", default="timestamp",
                      help="path of the reading time, Unix seconds or ISO 8601 (default timestamp)")

    th = p.add_argument_group("thresholds")
    th.add_argument("-w", "--warning", type=range_arg, metavar="RANGE", help="temperature warning range")
    th.add_argument("-c", "--critical", type=range_arg, metavar="RANGE", help="temperature critical range")
    th.add_argument("-W", "--humidity-warning", type=range_arg, metavar="RANGE", help="humidity warning range (%%)")
    th.add_argument("-C", "--humidity-critical", type=range_arg, metavar="RANGE", help="humidity critical range (%%)")
    th.add_argument("--unit", choices=["C", "F", "c", "f"], default="C",
                    help="unit for temperature thresholds, output and perfdata (default C)")
    th.add_argument("--require-humidity", action="store_true",
                    help="UNKNOWN when the document has no humidity (default: humidity is optional)")
    th.add_argument("--max-age", type=int, metavar="SECONDS",
                    help="CRITICAL when the reading is older than this (needs the timestamp)")
    th.add_argument("--age-warning", type=int, metavar="SECONDS",
                    help="WARNING when the reading is older than this (needs the timestamp)")

    p.add_argument("-t", "--timeout", type=timeout_arg, default=(10, UNKNOWN), metavar="SECONDS[:STATE]",
                   help="plugin timeout, default 10; STATE on timeout: unknown (default), warning or critical")
    p.add_argument("-v", "--verbose", action="count", default=0, help="more output (repeat for more)")
    p.add_argument("-V", "--version", action="version", version="%s %s" % (PROG, VERSION))
    return p


def fmt(x):
    """Plain number for output and perfdata: up to 2 decimals, no trailing zeros."""
    s = ("%.2f" % x).rstrip("0").rstrip(".")
    return "0" if s in ("-0", "") else s


def perf(label, value, uom, warn, crit, vmin="", vmax=""):
    return "%s=%s%s;%s;%s;%s;%s" % (
        label, fmt(value), uom,
        warn.text if warn else "", crit.text if crit else "",
        vmin, vmax,
    )


def run(args):
    if not (args.url or args.hostname or args.file):
        raise PluginError(UNKNOWN, "give -H HOST, -U URL or -f FILE")
    if sum(1 for x in (args.url, args.hostname, args.file) if x) > 1:
        raise PluginError(UNKNOWN, "use only one of -H, -U and -f")
    if args.port is not None and not 0 < args.port < 65536:
        raise PluginError(UNKNOWN, "port must be 1..65535")
    for name in ("max_age", "age_warning"):
        v = getattr(args, name)
        if v is not None and v < 1:
            raise PluginError(UNKNOWN, "--%s must be at least 1 second" % name.replace("_", "-"))

    seconds, _ = args.timeout
    if args.file:
        source = args.file
        body = read_file(args.file)
    else:
        source = build_url(args)
        body = fetch(source, args, seconds)

    try:
        doc = json.loads(body.decode("utf-8-sig"))
    except (UnicodeDecodeError, ValueError) as exc:
        raise PluginError(UNKNOWN, "response from %s is not valid JSON (%s)" % (source, exc))

    found, raw_temp = lookup(doc, args.temp_key)
    if not found:
        raise PluginError(UNKNOWN, "no '%s' in the JSON from %s" % (args.temp_key, source))
    temp_in = as_number(raw_temp, "temperature '%s'" % args.temp_key)

    if args.input_unit:
        src_unit = args.input_unit.upper()
    else:
        found_u, raw_u = lookup(doc, args.unit_key)
        src_unit = parse_unit(raw_u, "unit '%s'" % args.unit_key) if found_u and raw_u is not None else "C"
    unit = args.unit.upper()
    temp = convert(temp_in, src_unit, unit)

    found_h, raw_h = lookup(doc, args.humidity_key)
    humidity = None
    if found_h and raw_h is not None:
        humidity = as_number(raw_h, "humidity '%s'" % args.humidity_key)
        if not 0 <= humidity <= 100:
            raise PluginError(UNKNOWN, "humidity %s %% is outside 0..100 (sensor error?)" % fmt(humidity))
    elif args.require_humidity or args.humidity_warning or args.humidity_critical:
        raise PluginError(UNKNOWN, "no '%s' in the JSON from %s" % (args.humidity_key, source))

    age = None
    if args.max_age or args.age_warning:
        found_t, raw_t = lookup(doc, args.timestamp_key)
        if not found_t or raw_t is None:
            raise PluginError(UNKNOWN, "--max-age/--age-warning need '%s' in the JSON" % args.timestamp_key)
        age = time.time() - parse_timestamp(raw_t)
        if age < -300:
            raise PluginError(UNKNOWN, "the reading is %d s in the future: check the sensor's clock" % -age)
        age = max(age, 0.0)

    states = []
    t_state = evaluate(temp, args.warning, args.critical)
    states.append(t_state)
    parts = ["temperature %s %s" % (fmt(temp), unit)]
    if t_state != OK:
        parts[-1] += " (%s)" % STATE_NAMES[t_state]
    label = "temperature_%s" % unit.lower()
    perfdata = [perf(label, temp, "", args.warning, args.critical)]

    if humidity is not None:
        h_state = evaluate(humidity, args.humidity_warning, args.humidity_critical)
        states.append(h_state)
        parts.append("humidity %s %%" % fmt(humidity))
        if h_state != OK:
            parts[-1] += " (%s)" % STATE_NAMES[h_state]
        perfdata.append(perf("humidity", humidity, "%", args.humidity_warning, args.humidity_critical, "0", "100"))

    if age is not None:
        a_state = OK
        if args.max_age and age > args.max_age:
            a_state = CRITICAL
        elif args.age_warning and age > args.age_warning:
            a_state = WARNING
        states.append(a_state)
        parts.append("reading %d s old" % int(age))
        if a_state != OK:
            parts[-1] += " (%s)" % STATE_NAMES[a_state]
        perfdata.append("age=%ds;%s;%s;0;" % (int(age), args.age_warning or "", args.max_age or ""))

    state = max(states)  # OK 0 < WARNING 1 < CRITICAL 2; UNKNOWN cases raised above
    long_lines = []
    if args.verbose:
        long_lines.append("source: %s" % source)
        long_lines.append("temperature in document: %s %s (key %s)" % (fmt(temp_in), src_unit, args.temp_key))
    if args.verbose >= 2:
        long_lines.append("document: %s" % json.dumps(doc, sort_keys=True)[:2000])
    finish(state, ", ".join(parts), perfdata, long_lines)


def main(argv=None):
    parser = make_parser()
    args = parser.parse_args(argv)
    seconds, t_state = args.timeout

    def on_alarm(signum, frame):
        finish(t_state, "plugin timed out after %d s" % seconds)

    if hasattr(signal, "SIGALRM"):
        signal.signal(signal.SIGALRM, on_alarm)
        signal.alarm(seconds + 1)  # backstop; the socket timeout normally fires first
    try:
        run(args)
    except PluginError as exc:
        finish(exc.state, exc.message)
    except TimeoutError:
        finish(t_state, "no answer within %d s" % seconds)
    except KeyboardInterrupt:
        finish(UNKNOWN, "interrupted")
    except Exception as exc:  # never leave the monitoring system with a traceback and exit 1
        finish(UNKNOWN, "internal error: %s: %s" % (type(exc).__name__, exc))


if __name__ == "__main__":
    main()
