#!/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 json
import sys

import lib.args
import lib.base
import lib.lftest
import lib.shell
from lib.globals import STATE_OK, STATE_UNKNOWN, STATE_WARN

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

DESCRIPTION = """Verifies the integrity of a restic backup repository by running "restic check". Alerts
when the repository contains errors or inconsistencies.
Requires root or sudo."""


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(
        '--password-file',
        help='Path to the file containing the repository password.',
        dest='PASSWORD_FILE',
    )

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

    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)

    # fetch data
    if args.TEST is None:
        cmd = f'restic --json --repo={args.REPO} --password-file={args.PASSWORD_FILE} check'
        stdout, stderr, retc = lib.base.coe(lib.shell.shell_exec(cmd))
    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:
        # 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 = f'There are warnings.\n\n{stderr}'
        state = STATE_WARN

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


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