#!/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.wildfly
from lib.globals import STATE_OK, STATE_UNKNOWN

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

DESCRIPTION = """Checks Java heap and non-heap memory usage on a WildFly/JBoss AS server via its HTTP
management API. Alerts when memory usage exceeds the configured thresholds."""

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


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(
        '--critical',
        help=lib.args.help('--critical') + ' Default: >= %(default)s',
        dest='CRIT',
        default=DEFAULT_CRIT,
    )

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

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

    parser.add_argument(
        '--mode',
        help='WildFly server mode. Default: %(default)s',
        dest='MODE',
        choices=['standalone', 'domain'],
        default='standalone',
    )

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

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

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

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

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

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

    parser.add_argument(
        '--warning',
        help=lib.args.help('--warning') + ' Default: >= %(default)s',
        dest='WARN',
        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)

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

    # fetch data
    # https://docs.wildfly.org/23/Admin_Guide.html

    data = {
        'operation': 'read-resource',
        'include-runtime': 'true',
        # /core-service/platform-mbean/type/memory
        'address': [{'core-service': 'platform-mbean'}, {'type': 'memory'}],
        'json': 1,
    }
    res = lib.wildfly.get_data(args, data)

    mem_used = res['heap-memory-usage']['used']
    mem_committed = res['heap-memory-usage']['committed']
    mem_max = res['heap-memory-usage']['max']

    used_percent = round((float(mem_used) / float(mem_max) * 100), 2)
    used_state = lib.base.get_state(used_percent, args.WARN, args.CRIT, 'ge')
    committed_percent = round((float(mem_committed) / float(mem_max) * 100), 2)
    committed_state = lib.base.get_state(committed_percent, args.WARN, args.CRIT, 'ge')


    # build the message
    msg += (
        f'Heap used: {used_percent}%'
        f' ({lib.human.bytes2human(mem_used)}'
        f' of {lib.human.bytes2human(mem_max)})'
        f'{lib.base.state2str(used_state, prefix=" ")}'
        f', Heap committed: {committed_percent}%'
        f' ({lib.human.bytes2human(mem_committed)}'
        f' of {lib.human.bytes2human(mem_max)})'
        f'{lib.base.state2str(committed_state, prefix=" ")}'
        f', '
    )
    state = lib.base.get_worst(state, used_state, committed_state)
    perfdata += lib.base.get_perfdata(
        'heap-used-percent',
        used_percent,
        uom='%',
        warn=args.WARN,
        crit=args.CRIT,
        _min=0,
        _max=100,
    )
    perfdata += lib.base.get_perfdata(
        'heap-committed-percent',
        committed_percent,
        uom='%',
        warn=args.WARN,
        crit=args.CRIT,
        _min=0,
        _max=100,
    )
    perfdata += lib.base.get_perfdata(
        'heap-used',
        mem_used,
        uom='B',
        _min=0,
        _max=mem_max,
    )
    perfdata += lib.base.get_perfdata(
        'heap-max',
        mem_max,
        uom='B',
        _min=0,
        _max=mem_max,
    )
    perfdata += lib.base.get_perfdata(
        'heap-committed',
        mem_committed,
        uom='B',
        _min=0,
        _max=mem_max,
    )

    mem_used = res['non-heap-memory-usage']['used']
    mem_committed = res['non-heap-memory-usage']['committed']
    mem_max = res['non-heap-memory-usage']['max']

    used_percent = round((float(mem_used) / float(mem_max) * 100), 2)
    used_state = lib.base.get_state(used_percent, args.WARN, args.CRIT, 'ge')
    committed_percent = round((float(mem_committed) / float(mem_max) * 100), 2)
    committed_state = lib.base.get_state(committed_percent, args.WARN, args.CRIT, 'ge')

    msg += (
        f'Non-Heap used: {used_percent}%'
        f' ({lib.human.bytes2human(mem_used)}'
        f' of {lib.human.bytes2human(mem_max)})'
        f'{lib.base.state2str(used_state, prefix=" ")}'
        f', Non-Heap committed: {committed_percent}%'
        f' ({lib.human.bytes2human(mem_committed)}'
        f' of {lib.human.bytes2human(mem_max)})'
        f'{lib.base.state2str(committed_state, prefix=" ")}'
        f', '
    )
    state = lib.base.get_worst(state, used_state, committed_state)
    perfdata += lib.base.get_perfdata(
        'non-heap-used-percent',
        used_percent,
        uom='%',
        warn=args.WARN,
        crit=args.CRIT,
        _min=0,
        _max=100,
    )
    perfdata += lib.base.get_perfdata(
        'non-heap-committed-percent',
        committed_percent,
        uom='%',
        warn=args.WARN,
        crit=args.CRIT,
        _min=0,
        _max=100,
    )
    perfdata += lib.base.get_perfdata(
        'non-heap-used',
        mem_used,
        uom='B',
        _min=0,
        _max=mem_max,
    )
    perfdata += lib.base.get_perfdata(
        'non-heap-max',
        mem_max,
        uom='B',
        _min=0,
        _max=mem_max,
    )
    perfdata += lib.base.get_perfdata(
        'non-heap-committed',
        mem_committed,
        uom='B',
        _min=0,
        _max=mem_max,
    )

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


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