#!/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.db_mysql  # pylint: disable=C0413
from lib.globals import (STATE_OK, STATE_UNKNOWN,  # pylint: disable=C0413
                          STATE_WARN)

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

DESCRIPTION = """Checks for missing indexes in MySQL/MariaDB tables."""

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='{0}: v{1} by {2}'.format('%(prog)s', __version__, __author__)
    )

    parser.add_argument(
        '--always-ok',
        help='Always returns OK.',
        dest='ALWAYS_OK',
        action='store_true',
        default=False,
    )

    parser.add_argument(
        '--defaults-file',
        help='Specifies a cnf file to read parameters like user, host and password from '
             '(instead of specifying them on the command line), '
             'for example `/var/spool/icinga2/.my.cnf`. Default: %(default)s',
        dest='DEFAULTS_FILE',
        default=DEFAULT_DEFAULTS_FILE,
    )

    parser.add_argument(
        '--defaults-group',
        help='Group/section to read from in the cnf file. Default: %(default)s',
        dest='DEFAULTS_GROUP',
        default=DEFAULT_DEFAULTS_GROUP,
    )

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

    return parser.parse_args()


def main():
    """The main function. Hier spielt die Musik.
    """

    # logic taken from mysqltuner.pl:mysql_tables(), v1.9.8
    # including variable names

    # parse the command line, exit with UNKNOWN if it fails
    try:
        args = parse_args()
    except SystemExit:
        sys.exit(STATE_UNKNOWN)

    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))

    # init some vars
    msg = ''
    state = STATE_OK
    tables = []

    # TABLE_SCHEMA and TABLE_NAME must be uppercase due to MySQL 8+
    sql = '''
        select distinct TABLE_SCHEMA
        from information_schema.tables
        where TABLE_SCHEMA not in (
            "mysql", "information_schema", "performance_schema", "percona", "sys"
        );
    '''
    user_dbs = lib.base.coe(lib.db_mysql.select(conn, sql))

    for schema in user_dbs:
        sql = '''
            select TABLE_NAME
            from information_schema.tables
            where TABLE_SCHEMA="{}"
                and table_type="BASE TABLE"
            order by TABLE_NAME;
        '''.format(schema['TABLE_SCHEMA'])
        user_tables = lib.base.coe(lib.db_mysql.select(conn, sql))

        for table in user_tables:
            sql = '''
                select index_name as idxname,
                    group_concat(column_name order by seq_in_index) as cols,
                    index_type as type
                from information_schema.statistics
                where index_schema="{}"
                    and TABLE_NAME="{}"
                group by idxname, type;
            '''.format(schema['TABLE_SCHEMA'], table['TABLE_NAME'])
            user_indexes = lib.base.coe(lib.db_mysql.select(conn, sql))
            if len(user_indexes) == 0:
                tables.append('{}.{}'.format(schema['TABLE_SCHEMA'], table['TABLE_NAME']))

    lib.db_mysql.close(conn)

    if not tables:
        msg = 'Everything is ok.'
    else:
        state = STATE_WARN
        msg = 'Tables without indexes {}:\n* {}'.format(
            lib.base.state2str(state),
            '\n* '.join(tables),
        )

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


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