#!/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 tempfile

import lib.args
import lib.base
import lib.disk
from lib.globals import STATE_OK, STATE_UNKNOWN

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

DESCRIPTION = """Tests if a path is writable and readable by creating, writing, reading, and deleting
a temporary file. Especially useful for mounted filesystems such as NFS or SMB where
the mount may silently become read-only or unresponsive. The local temporary directory
is always tested as a baseline.
Alerts if the path is not writable or readable.
Requires root or sudo."""

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=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(
        '--path',
        help='Path to test for read/write access by creating and deleting a temporary file. '
        'Can be specified multiple times. '
        'Default: %(default)s',
        dest='PATH',
        default=DEFAULT_PATH,
        action='append',
    )

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

    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

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

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

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


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