#!/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.db_mysql
import lib.human
import lib.txt
from lib.globals import STATE_OK, STATE_UNKNOWN, STATE_WARN

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

DESCRIPTION = """Checks the InnoDB buffer pool instance configuration in MySQL/MariaDB. Alerts if the
configuration does not follow best practices for the given buffer pool size."""

DEFAULT_DEFAULTS_FILE = '/var/spool/icinga2/.my.cnf'
DEFAULT_DEFAULTS_GROUP = 'client'
DEFAULT_TIMEOUT = 3


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(
        '--defaults-file',
        help='MySQL/MariaDB cnf file to read user, host and password from (instead of specifying them on the command line). '
        'Example: `/var/spool/icinga2/.my.cnf`. '
        'Default: %(default)s',
        dest='DEFAULTS_FILE',
        default=DEFAULT_DEFAULTS_FILE,
    )

    parser.add_argument(
        '--defaults-group',
        help=lib.args.help('--defaults-group') + ' Default: %(default)s',
        dest='DEFAULTS_GROUP',
        default=DEFAULT_DEFAULTS_GROUP,
    )

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

    args, _ = parser.parse_known_args()
    return args


def get_vars(conn):
    # Do not implement `get_all_vars()`, just fetch the ones we need for this check.
    # Without the GLOBAL modifier, SHOW VARIABLES displays the values that are used for
    # the current connection to MariaDB.
    sql = """
        show global variables
        where variable_name like 'innodb_buffer_pool_instances'
            or variable_name like 'innodb_buffer_pool_size'
            ;
          """
    return lib.base.coe(lib.db_mysql.select(conn, sql))


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

    # logic taken from mysqltuner.pl:mysql_innodb(), section # InnoDB Buffer Pool Instances, v1.9.8
    # including variable names

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

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

    mysql_connection = {
        'defaults_file': args.DEFAULTS_FILE,
        'defaults_group': args.DEFAULTS_GROUP,
        'timeout': args.TIMEOUT,
    }
    conn = lib.base.coe(lib.db_mysql.connect(mysql_connection))
    lib.base.coe(lib.db_mysql.check_select_privileges(conn))

    engines = lib.db_mysql.get_engines(conn)
    if not engines.get('have_innodb', ''):
        lib.db_mysql.close(conn)
        lib.base.cu('InnoDB Storage Engine not available.')
    if engines['have_innodb'] != 'YES':
        lib.db_mysql.close(conn)
        lib.base.cu('InnoDB Storage Engine is disabled.')

    myvar = lib.db_mysql.lod2dict(get_vars(conn))
    lib.db_mysql.close(conn)

    # InnoDB Buffer Pool Instances
    if myvar.get('innodb_buffer_pool_instances', None) is None:
        # Removed in MariaDB 10.6.0
        lib.base.oao('Everything is ok (although nothing checked).', state)

    instances = myvar['innodb_buffer_pool_instances']

    # build the message
    msg += (
        f'{instances} InnoDB buffer pool'
        f' {lib.txt.pluralize("instance", int(instances))}'
    )

    # Bad Value if > 64
    if int(myvar['innodb_buffer_pool_instances']) > 64:
        inst1_state = STATE_WARN
        state = lib.base.get_worst(state, inst1_state)
        inst1_str = lib.base.state2str(inst1_state, prefix=' ')
        msg += f'{inst1_str}. Set innodb_buffer_pool_instances <= 64. '
    else:
        msg += '. '

    # InnoDB Buffer Pool Size > 1Go
    if int(myvar['innodb_buffer_pool_size']) > 1024 * 1024 * 1024:
        # InnoDB Buffer Pool Size / 1Go = InnoDB Buffer Pool Instances limited to 64 max.
        # InnoDB Buffer Pool Size > 64Go
        max_innodb_buffer_pool_instances = min(
            int(int(myvar['innodb_buffer_pool_size']) / (1024 * 1024 * 1024)), 64
        )
        if (
            int(myvar['innodb_buffer_pool_instances'])
            != max_innodb_buffer_pool_instances
        ):
            inst2_state = STATE_WARN
            state = lib.base.get_worst(state, inst2_state)
            inst2_str = lib.base.state2str(
                inst2_state,
                prefix=' ',
            )
            msg += (
                f'Set innodb_buffer_pool_instances'
                f' to {max_innodb_buffer_pool_instances}'
                f'{inst2_str}. '
            )
    else:
        if int(myvar['innodb_buffer_pool_instances']) != 1:
            inst2_state = STATE_WARN
            state = lib.base.get_worst(state, inst2_state)
            inst2_str = lib.base.state2str(
                inst2_state,
                prefix=' ',
            )
            msg += (
                f'innodb_buffer_pool_size <= 1G and'
                f' innodb_buffer_pool_instances'
                f' !=1{inst2_str}. Set'
                f' innodb_buffer_pool_instances to 1.'
            )

    perfdata += lib.base.get_perfdata(
        'mysql_innodb_buffer_pool_instances',
        myvar['innodb_buffer_pool_instances'],
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'mysql_innodb_buffer_pool_size',
        myvar['innodb_buffer_pool_size'],
        uom='B',
        _min=0,
    )

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


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