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

import lib.args  # pylint: disable=C0413
import lib.base  # pylint: disable=C0413
import lib.shell  # pylint: disable=C0413
import lib.lftest  # pylint: disable=C0413
from lib.globals import (STATE_OK, STATE_UNKNOWN,  # pylint: disable=C0413
                          STATE_WARN)

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

DESCRIPTION = """Check the restic repository for errors."""


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(
        '--password-file',
        help='File to read the repository password from',
        dest='PASSWORD_FILE',
    )

    parser.add_argument(
        '--repo',
        help='Repository location',
        dest='REPO',
        required=True,
    )

    parser.add_argument(
        '--test',
        help='For unit tests. Needs "path-to-stdout-file,path-to-stderr-file,expected-retc".',
        dest='TEST',
        type=lib.args.csv,
    )

    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)

    # fetch data
    if args.TEST is None:
        cmd = 'restic --json --repo={} --password-file={} check'.format(
            args.REPO,
            args.PASSWORD_FILE,
        )
        stdout, stderr, retc = lib.base.coe(lib.shell.shell_exec(cmd)) # pylint: disable=W0612
    else:
        # do not call the command, put in test data
        stdout, stderr, retc = lib.lftest.test(args.TEST)

    is_json = True
    try:
        json.loads(stdout)
    except ValueError as e:
        # cmd is not json-capable in restic v0.13.1, but maybe in the future
        is_json = False
    if is_json:
        lib.base.cu('JSON is currently not implemented.')

    # init some vars
    msg = ''
    state = STATE_OK

    # analyze data and build the message
    if retc == 0 and 'no errors' in stdout:
        msg = 'Everything is ok.'
    else:
        cnt = stderr.count('\n') + 1
        if cnt > 10:
            # shorten the message
            stderr = stderr.split('\n')
            stderr = stderr[0:5] + ['...'] + stderr[-5:]
            stderr = '\n'.join(stderr)
        msg = 'There are warnings.\n\n{}'.format(stderr)
        state = STATE_WARN

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


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