#!/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 tempfile  # pylint: disable=C0413

import lib.base  # pylint: disable=C0413
import lib.disk  # pylint: disable=C0413
from lib.globals import (STATE_CRIT, STATE_OK,  # pylint: disable=C0413
                          STATE_UNKNOWN, STATE_WARN)

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

DESCRIPTION = """Tests if a temporary file can be created, written to a specified path, read,
                 and then deleted. Especially useful with mounted file systems such as NFS or SMB.
                 The local temporary directory is always tested, regardless of whether the check is
                 called with or without parameters. May require sudo privileges."""

DEFAULT_PATH = [tempfile.gettempdir()]
DEFAULT_SEVERITY = 'warn'


def parse_args():
    """Parse command line arguments using argparse.
    """
    parser = argparse.ArgumentParser(description=DESCRIPTION)

    parser.add_argument(
        '-V', '--version',
        action='version',
        version='%(prog)s: v{} by {}'.format(__version__, __author__)
    )

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

    parser.add_argument('--path',
        help='Path to which the file is to be written and from which it will be deleted '
             '(repeating). Default: %(default)s',
        dest='PATH',
        default=DEFAULT_PATH,
        action='append',
    )

    parser.add_argument(
        '--severity',
        help='Severity for alerting. Default: %(default)s',
        dest='SEVERITY',
        default=DEFAULT_SEVERITY,
        choices=['warn', 'crit'],
    )

    return parser.parse_args()


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

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

    # init some vars
    msg = ''
    state = STATE_OK

    # do the test
    for path in args.PATH:
        try:
            fp = tempfile.TemporaryFile(dir=path)
            # a bytes-like object is required, not 'str':
            fp.write(b'Linuxfabrik GmbH, Zurich, Switzerland')
            fp.seek(0)
            fp.read()
            # close the file, it will be removed
            fp.close()
        except Exception as e:
            msg += '`{}` ({}), '.format(path, e)
            state = lib.base.str2state(args.SEVERITY)

    # build the message
    if msg == '':
        msg = 'Everything is ok. '
    else:
        msg = 'Error creating/writing/reading/deleting file in {}. '.format(msg[:-2])
    msg += 'Tested: {}'.format(', '.join(args.PATH))

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