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

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

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

DESCRIPTION = """Monitors available Grassfish digital signage licenses via the Grassfish API. Alerts
when no more licenses are available. Requires a Grassfish hostname and API token."""

DEFAULT_API_VERSION = '1.12'
DEFAULT_INSECURE = False
DEFAULT_NO_PROXY = False
DEFAULT_PORT = '443'
DEFAULT_TIMEOUT = 8
DEFAULT_URL = '/gv2/webservices/API'


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(
        '--api-version',
        help='Grassfish API version. Default: %(default)s',
        dest='API_VERSION',
        default=DEFAULT_API_VERSION,
    )

    parser.add_argument(
        '-H',
        '--hostname',
        help='Grassfish hostname.',
        dest='HOSTNAME',
        required=True,
    )

    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(
        '--port',
        help='Grassfish port number. Default: %(default)s',
        dest='PORT',
        type=int,
        default=DEFAULT_PORT,
    )

    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(
        '--token',
        help='Grassfish API token.',
        dest='TOKEN',
        required=True,
    )

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

    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.base.coe(
            lib.grassfish.fetch_json(
                args.TOKEN,
                args.HOSTNAME,
                args.PORT,
                args.URL,
                args.API_VERSION,
                'Licenses',
                insecure=args.INSECURE,
                no_proxy=args.NO_PROXY,
                timeout=args.TIMEOUT,
            )
        )
    else:
        # do not call the command, put in test data
        stdout, _stderr, _retc = lib.lftest.test(args.TEST)
        result = json.loads(stdout)

    # init some vars
    msg = ''
    state = STATE_OK
    perfdata = ''
    table_data = []

    # analyze data
    for lic in result:
        used = lic['TotalCount'] - lic['AvailableCount']
        if lic['AvailableCount'] == 0:
            lic_state = STATE_WARN
            msg += f'{lic["Type"]}, '
        else:
            lic_state = STATE_OK

        state = lib.base.get_worst(state, lic_state)
        table_data.append(
            {
                'type': lic['Type'],
                'usage': (
                    f'{used}/{lic["TotalCount"]}'
                    f' ({lic["AvailableCount"]} available'
                    f'{lib.base.state2str(lic_state, prefix=" ")})'
                ),
            }
        )
        perfdata += lib.base.get_perfdata(
            f'grassfish_lic_{lic["Type"].lower()}_used',
            used,
            _min=0,
            _max=lic['TotalCount'],
        )

    # build the message
    keys = []
    headers = []
    if table_data:
        keys = [
            'type',
            'usage',
        ]
        headers = [
            'License Type',
            'Usage',
        ]

    if state == STATE_OK:
        msg = 'Everything is ok.\n\n'
    else:
        msg = f'No more licenses available: {msg[:-2]}\n\n'
    msg += lib.base.get_table(table_data, keys, header=headers)

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


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