#!/usr/bin/env python3
# -*- coding: utf-8; py-indent-offset: 4 -*-
#
# Author:  Linuxfabrik GmbH, Zurich, Switzerland
# Contact: info (at) linuxfabrik (dot) ch
#          https://www.linuxfabrik.ch/
# License: The Unlicense, see LICENSE file.

# https://github.com/Linuxfabrik/monitoring-plugins/blob/main/CONTRIBUTING.md

"""See the check's README for more details.
"""

import warnings

warnings.filterwarnings("ignore")
import argparse  # pylint: disable=C0413
import sys  # pylint: disable=C0413

import lib.base  # pylint: disable=C0413
from lib.globals import (STATE_CRIT, STATE_OK,  # pylint: disable=C0413
                          STATE_UNKNOWN, STATE_WARN)

try:
    import psutil  # pylint: disable=C0413
except ImportError:
    print('Python module "psutil" is not installed.')
    sys.exit(STATE_UNKNOWN)


__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
__version__ = '2025020401'

DESCRIPTION = """Return certain hardware temperature sensors (it may be a CPU, an hard disk or
                 something else, depending on the OS and its configuration). All temperatures are
                 expressed in celsius. Check is done automatically against hardware thresholds. If
                 sensors are not supported by the OS OK is returned."""


def parse_args():
    """Parse command line arguments using argparse.
    """
    parser = argparse.ArgumentParser(description=DESCRIPTION)

    parser.add_argument(
        '-V', '--version',
        action='version',
        version='%(prog)s: v{} by {}'.format(__version__, __author__)
    )

    parser.add_argument(
        '--always-ok',
        help='Always returns OK.',
        dest='ALWAYS_OK',
        action='store_true',
        default=False,
    )

    return parser.parse_args()


def main():
    """The main function. Hier spielt die Musik.
    """

    # parse the command line, exit with UNKNOWN if it fails
    try:
        args = parse_args()
    except SystemExit:
        sys.exit(STATE_UNKNOWN)

    if not hasattr(psutil, 'sensors_temperatures'):
        lib.base.cu('Platform not supported.')

    # fetch data
    temps = psutil.sensors_temperatures()
    if not temps:
        lib.base.oao('Can\'t read any temperature.', STATE_OK, always_ok=args.ALWAYS_OK)

    msg = ''
    state = STATE_OK
    perfdata = ''

    for name, entries in temps.items():
        msg += '* {}: '.format(name)
        for entry in entries:
            perfdata += lib.base.get_perfdata('{}_{}'.format(name, entry.label).replace(' ', '_').lower(), entry.current, None, entry.high, entry.critical, 0, None)
            sensor_state = lib.base.get_state(entry.current, entry.high, entry.critical, 'ge')
            msg += '{} = {}°C '.format(entry.label or name, entry.current)
            msg += lib.base.state2str(sensor_state)
            msg = msg.strip() + ', '
            state = lib.base.get_worst(state, sensor_state)
        msg = msg[:-2] + '\n'

    # over and out
    lib.base.oao(msg[:-2], state, perfdata, always_ok=args.ALWAYS_OK)


if __name__ == '__main__':
    try:
        main()
    except Exception:   # pylint: disable=W0703
        lib.base.cu()
