#!/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 argparse
import sys

import lib.args
import lib.base
import lib.human
import lib.lftest
import lib.nodebb
from lib.globals import STATE_OK, STATE_UNKNOWN

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

DESCRIPTION = """Retrieves NodeBB process and system information via the admin API, including Node.js
version, uptime, memory usage, and Git commit hash.
Alerts when memory usage exceeds the configured thresholds."""

DEFAULT_CRIT = 95
DEFAULT_INSECURE = False
DEFAULT_NO_PROXY = False
DEFAULT_TIMEOUT = 3
DEFAULT_URL = 'http://localhost:4567/forum'
DEFAULT_WARN = 90


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

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

    parser.add_argument(
        '--always-ok',
        help=lib.args.help('--always-ok'),
        dest='ALWAYS_OK',
        action='store_true',
        default=False,
    )

    parser.add_argument(
        '-c',
        '--critical',
        help=lib.args.help('--critical') + ' Default: >= %(default)s',
        dest='CRIT',
        type=int,
        default=DEFAULT_CRIT,
    )

    parser.add_argument(
        '--insecure',
        help=lib.args.help('--insecure'),
        dest='INSECURE',
        action='store_true',
        default=DEFAULT_INSECURE,
    )

    parser.add_argument(
        '--no-proxy',
        help=lib.args.help('--no-proxy'),
        dest='NO_PROXY',
        action='store_true',
        default=DEFAULT_NO_PROXY,
    )

    parser.add_argument(
        '--test',
        help=lib.args.help('--test'),
        dest='TEST',
        type=lib.args.csv,
    )

    parser.add_argument(
        '--timeout',
        help=lib.args.help('--timeout') + ' Default: %(default)s (seconds)',
        dest='TIMEOUT',
        type=int,
        default=DEFAULT_TIMEOUT,
    )

    parser.add_argument(
        '-p',
        '--token',
        help='NodeBB API bearer token.',
        dest='TOKEN',
        required=True,
    )

    parser.add_argument(
        '--url',
        help='NodeBB API URL. Default: %(default)s',
        dest='URL',
        default=DEFAULT_URL,
    )

    parser.add_argument(
        '-w',
        '--warning',
        help=lib.args.help('--warning') + ' Default: >= %(default)s',
        dest='WARN',
        type=int,
        default=DEFAULT_WARN,
    )

    args, _ = parser.parse_known_args()
    return args


def main():
    """The main function. This is where the magic happens."""

    # parse the command line
    try:
        args = parse_args()
    except SystemExit:
        sys.exit(STATE_UNKNOWN)

    # fetch data
    if args.TEST is None:
        result = lib.nodebb.get_data(args, '/api/admin/development/info')
    else:
        # do not call the command, put in test data
        import json

        stdout, _stderr, _retc = lib.lftest.test(args.TEST)
        result = json.loads(stdout)

    # init some vars
    msg = ''
    state = STATE_OK
    perfdata = ''

    # analyze data
    for proc in result['info']:
        if proc['process']['title'].endswith('/node'):
            try:
                heap_used_percent = round(
                    float(proc['process']['memoryUsage']['heapUsed'])
                    / float(proc['process']['memoryUsage']['heapTotal'])
                    * 100,
                    1,
                )
                heap_state = lib.base.get_state(heap_used_percent, args.WARN, args.CRIT)
                state = lib.base.get_worst(state, heap_state)
                mem = proc['process']['memoryUsage']

                # build the message
                msg += (
                    f'NodeBB {proc["id"]}'
                    f', {proc["process"]["title"]}'
                    f' {proc["process"]["version"]}'
                    f', Heap {heap_used_percent}% used'
                    f' ({lib.human.bytes2human(mem["heapUsed"])}'
                    f' of {lib.human.bytes2human(mem["heapTotal"])})'
                    f'{lib.base.state2str(heap_state, prefix=" ")}'
                    f', RSS {lib.human.bytes2human(mem["rss"])}'
                    f', Up {lib.human.seconds2human(proc["process"]["uptime"])}'
                )

                perfdata += lib.base.get_perfdata(
                    'nodebb_heap_used_percent',
                    heap_used_percent,
                    uom='%',
                    warn=args.WARN,
                    crit=args.CRIT,
                    _min=0,
                    _max=100,
                )
                perfdata += lib.base.get_perfdata(
                    'nodebb_heap_used',
                    proc['process']['memoryUsage']['heapUsed'],
                    uom='B',
                    _min=0,
                    _max=proc['process']['memoryUsage']['heapTotal'],
                )
                perfdata += lib.base.get_perfdata(
                    'nodebb_rss',
                    proc['process']['memoryUsage']['rss'],
                    uom='B',
                    _min=0,
                )
                perfdata += lib.base.get_perfdata(
                    'nodebb_uptime',
                    proc['process']['uptime'],
                    uom='s',
                    _min=0,
                )
            except Exception:
                pass

    # over and out
    lib.base.oao(msg, state, perfdata, always_ok=args.ALWAYS_OK)


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