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

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

DESCRIPTION = """Queries the Name Service Switch (NSS) for entries in system
databases such as group, hosts, networks, passwd, protocols, or services.
Alerts if the lookup fails or if a specific key is not found."""

DEFAULT_DATABASE = 'group'


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(
        '--database',
        default=DEFAULT_DATABASE,
        dest='DATABASE',
        help='NSS database to query. May be any database supported by "getent". '
        'Example: `--database passwd`. '
        'Default: %(default)s',
    )

    parser.add_argument(
        '--key',
        help='Lookup key to search for in the database. '
        'If not specified, all entries are fetched '
        '(unless the database does not support enumeration). '
        'Can be specified multiple times. '
        'Example: `--key root --key nobody`.',
        dest='KEY',
        action='append',
    )

    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)

    # build the getent command
    cmd = f'/usr/bin/getent {args.DATABASE}'
    if args.KEY:
        for key in args.KEY:
            cmd += f' {key}'

    # fetch data
    stdout, stderr, retc = lib.base.coe(lib.shell.shell_exec(cmd))
    if stderr:
        lib.base.cu(stderr)

    # init some vars
    count = len(stdout.strip().split('\n'))

    # build the message
    msg = ''
    state = STATE_UNKNOWN
    if retc == 0:
        msg = f'Everything is ok. Executed `{cmd}`, got {count} results.'
        state = STATE_OK
    elif retc == 1:
        msg = f'Missing arguments for `{cmd}`, or database "{args.DATABASE}" unknown.'
        state = STATE_UNKNOWN
    elif retc == 2:
        msg = (
            f'One or more supplied keys could not be found'
            f' in "{args.DATABASE}", executing `{cmd}`.'
        )
        state = STATE_WARN
    elif retc == 3:
        msg = (
            f'Multiple keys (enumeration) not supported on database "{args.DATABASE}".'
        )
        state = STATE_UNKNOWN

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


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