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

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

DESCRIPTION = """Displays LibreNMS instance information including version, database schema, Python and
RRDtool versions via the LibreNMS API. This check does not track new releases since
LibreNMS can update itself when running the Git version."""

DEFAULT_INSECURE = False
DEFAULT_NO_PROXY = False
DEFAULT_TIMEOUT = 3
DEFAULT_URL = 'http://localhost'


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(
        '--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(
        '--timeout',
        help=lib.args.help('--timeout') + ' Default: %(default)s (seconds)',
        dest='TIMEOUT',
        type=int,
        default=DEFAULT_TIMEOUT,
    )

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

    parser.add_argument(
        '--url',
        help='LibreNMS 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)

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

    # return LibreNMS instance information
    result = lib.librenms.get_data(args, '/api/v0/system')
    result = result['system'][0]

    # since 22.7.0-33:
    # {
    #     "local_ver": "24.2.0",
    #     "local_sha": "f3627462242a7ee711742fcbff5f61786e93bf62",
    #     "local_date": "2024-02-27T19:54:10+01:00",
    #     "local_branch": "HEAD",
    #     "db_schema": "2024_02_07_151845_custom_map_additions (290)",
    #     "php_ver": "8.1.27",
    #     "python_ver": "3.6.8",
    #     "database_ver": "MariaDB 10.6.17-MariaDB",
    #     "rrdtool_ver": "1.7.0",
    #     "netsnmp_ver": "5.8"
    # }


    # build the message
    msg += f'LibreNMS {result["local_ver"]}'
    if 'local_branch' in result:
        msg += f' (Git: {result["local_branch"]})'
    msg += ', '
    msg += f'DB-Schema {result["db_schema"]}, '
    try:
        msg += f'{result["database_ver"]}, '
    except Exception:
        msg += f'{result["mysql_ver"]}, '
    msg += f'Net-SNMP {result["netsnmp_ver"]}, '
    msg += f'PHP {result["php_ver"]}, '
    msg += f'Python {result["python_ver"]}, '
    msg += f'RRD-Tool {result["rrdtool_ver"]}'

    perfdata += lib.base.get_perfdata(
        'librenms-version',
        lib.version.version2float(result['local_ver']),
        _min=0,
    )
    try:
        perfdata += lib.base.get_perfdata(
            'db-version',
            lib.version.version2float(result['database_ver']),
            _min=0,
        )
    except Exception:
        perfdata += lib.base.get_perfdata(
            'db-version',
            lib.version.version2float(result['mysql_ver']),
            _min=0,
        )
    perfdata += lib.base.get_perfdata(
        'netsnmp-version',
        lib.version.version2float(result['netsnmp_ver']),
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'php-version',
        lib.version.version2float(result['php_ver']),
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'python-version',
        lib.version.version2float(result['python_ver']),
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'rrdtool-version',
        lib.version.version2float(result['rrdtool_ver']),
        _min=0,
    )

    # over and out
    lib.base.oao(msg, state, perfdata)


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