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

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

DESCRIPTION = """Checks for unexpectedly read-only mounted filesystems, such as a root filesystem
that switched to read-only due to disk errors. Ignores ramfs, squashfs (snapd),
and other pseudo-filesystems by default. Additional mountpoints can be excluded via
--ignore.
Alerts when a read-only filesystem is detected that should be writable."""

DEFAULT_IGNORE = ['/dev/loop', '/proc', '/run/credentials', '/snap', '/sys/fs']


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(
        '--ignore',
        help='Mount point prefix to ignore. '
        'All mount points starting with this value will be skipped. '
        'Can be specified multiple times. '
        'Example: `--ignore /sys/fs` ignores `/sys/fs/cgroup` and similar. '
        'Default: /dev/loop, /proc, /run/credentials, /snap, /sys/fs.',
        action='append',
        dest='IGNORE',
        default=None,
    )

    parser.add_argument(
        '--test',
        help=lib.args.help('--test'),
        dest='TEST',
        type=lib.args.csv,
    )

    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)

    # set default values for append parameters that were not specified
    if args.IGNORE is None:
        args.IGNORE = DEFAULT_IGNORE


    # fetch data
    if args.TEST is None:
        # get the values the normal way
        mounts = lib.base.coe(lib.disk.read_file('/proc/mounts'))
    else:
        # do not call the command, put in test data
        stdout, _, _ = lib.lftest.test(args.TEST)
        mounts = stdout

    cnt = 0
    ros = []  # read-only mount points
    for mount in mounts.splitlines():
        mnt = mount.split()
        if len(mnt) != 6:
            lib.base.oao(
                'Unexpected format of /proc/mounts.',
                STATE_UNKNOWN,
            )
        mount_spec = mnt[0]
        mount_point = mnt[1]
        mount_type = mnt[2]

        if mount_type in ['ramfs', 'squashfs']:
            continue
        mount_options = mnt[3]
        if any(mount_point.startswith(item) for item in args.IGNORE):
            continue
        cnt += 1
        if 'rw' in mount_options:
            continue
        ros.append(f'{mount_spec} on {mount_point} (type {mount_type})')

    # build the message
    if len(ros) > 0:
        msg = (
            f'{len(ros)} read-only mount {lib.txt.pluralize("point", len(ros))} found: '
        )
        if len(ros) == 1:
            # show mount point info on first line when there is only one hit
            msg += ros[0]
        else:
            for item in ros:
                msg += f'\n* {item}'
        state = STATE_WARN
    else:
        msg = (
            f'Everything is ok. {cnt} mount {lib.txt.pluralize("point", cnt)} checked.'
        )
        state = STATE_OK

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


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