#!/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  # pylint: disable=C0413
import sys  # pylint: disable=C0413

import lib.base  # pylint: disable=C0413
import lib.human  # pylint: disable=C0413
import lib.wildfly  # pylint: disable=C0413
from lib.globals import STATE_OK, STATE_UNKNOWN  # pylint: disable=C0413

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

DESCRIPTION = 'Prints the status of the Wildfly/JBossAS garbage collector.'

DEFAULT_INSECURE = False
DEFAULT_NO_PROXY = False
DEFAULT_TIMEOUT = 3
DEFAULT_URL = 'http://localhost:9990'
DEFAULT_USERNAME = 'wildfly-monitoring'


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(
        '--insecure',
        help='This option explicitly allows to perform "insecure" SSL connections. '
             'Default: %(default)s',
        dest='INSECURE',
        action='store_true',
        default=DEFAULT_INSECURE,
    )

    parser.add_argument(
        '--instance',
        help='The instance (server-config) to check if running in domain mode.',
        dest='INSTANCE',
    )

    parser.add_argument(
        '--mode',
        help='The mode the server is running.',
        dest='MODE',
        choices=['standalone', 'domain'],
        default='standalone',
    )

    parser.add_argument(
        '--no-proxy',
        help='Do not use a proxy. '
             'Default: %(default)s',
        dest='NO_PROXY',
        action='store_true',
        default=DEFAULT_NO_PROXY,
    )

    parser.add_argument(
        '--node',
        help='The node (host) if running in domain mode.',
        dest='NODE',
    )

    parser.add_argument(
        '-p', '--password',
        help='WildFly API password.',
        dest='PASSWORD',
        required=True,
    )

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

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

    parser.add_argument(
        '--username',
        help='WildFly API username. '
             'Default: %(default)s',
        dest='USERNAME',
        default=DEFAULT_USERNAME,
        required=True,
    )

    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)

    # fetch and analyze data
    # https://docs.wildfly.org/23/Admin_Guide.html
    data = {
        'operation': 'read-resource',
        'include-runtime': 'true',
        'recursive': 'true',
        # /core-service/platform-mbean/type/garbage-collector
        'address': [{'core-service': 'platform-mbean'}, {'type': 'garbage-collector'}],
        'json': 1,    }
    res = lib.wildfly.get_data(args, data)

    msg = ''
    perfdata = ''
    state = STATE_OK

    for name, value in res['name'].items():
        gc_time = value['collection-time']
        gc_count = value['collection-count']
        perfdata += lib.base.get_perfdata('garbage-collector-{}-collection-time'.format(name), gc_time, 'ms', None, None, 0, None)
        perfdata += lib.base.get_perfdata('garbage-collector-{}-collection-count'.format(name), gc_count, 'c', None, None, 0, None)
        msg += '{}: CollectionCount {}, CollectionTime {}; '.format(
            name,
            lib.human.number2human(gc_count),
            lib.human.seconds2human(float(gc_time)/1000),
        )

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


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