#!/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.human  # pylint: disable=C0413
import lib.infomaniak  # pylint: disable=C0413
import lib.lftest  # pylint: disable=C0413
import lib.time  # pylint: disable=C0413
import lib.txt  # pylint: disable=C0413
from lib.globals import (STATE_CRIT, STATE_OK,  # pylint: disable=C0413
                          STATE_UNKNOWN, STATE_WARN)

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

DESCRIPTION = """Checks your Infomaniak Swiss Backup product details via the Infomaniak API."""

DEFAULT_CRIT = 3  # days
DEFAULT_INSECURE = False
DEFAULT_NO_PROXY = False
DEFAULT_SEVERITY = 'warn'
DEFAULT_TIMEOUT = 8
DEFAULT_WARN = 5 # days


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(
        '--account-id',
        help='Infomaniak Account-ID',
        dest='ACCOUNT_ID',
        required=True,
    )

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

    parser.add_argument(
        '-c', '--critical',
        help='Set the critical for the expiration date in days. '
             'Default: %(default)s',
        dest='CRIT',
        type=int,
        default=DEFAULT_CRIT,
    )

    parser.add_argument(
        '--insecure',
        help='This option explicitly allows to perform "insecure" SSL connections. '
             'Default: %(default)s',
        dest='INSECURE',
        action='store_true',
        default=DEFAULT_INSECURE,
    )

    parser.add_argument(
        '--no-proxy',
        help='Do not use a proxy. '
             'Default: %(default)s',
        dest='NO_PROXY',
        action='store_true',
        default=DEFAULT_NO_PROXY,
    )

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

    parser.add_argument(
        '--timeout',
        help='Network timeout in seconds. '
             'Default: %(default)s (seconds)',
        dest='TIMEOUT',
        type=int,
        default=DEFAULT_TIMEOUT,
    )

    parser.add_argument(
        '--token',
        help='Infomaniak API token',
        dest='TOKEN',
        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,
    )

    parser.add_argument(
        '-w', '--warning',
        help='Set the warning for the expiration date in days. '
             'Default: %(default)s',
        dest='WARN',
        type=int,
        default=DEFAULT_WARN,
    )

    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:
        result = lib.base.coe(lib.infomaniak.get_swiss_backup_products(
            args.ACCOUNT_ID,
            args.TOKEN,
            insecure=args.INSECURE,
            no_proxy=args.NO_PROXY,
            timeout=args.TIMEOUT,
        ))
    else:
        # do not call the command, put in test data
        stdout, stderr, retc = lib.lftest.test(args.TEST)
        result = json.loads(stdout)

    # init some vars
    msg = ''
    state = STATE_OK
    perfdata = ''
    table_data = []

    # analyze data
    for product in result.get('data', {}):

        expired_at = product.get('expired_at') - lib.time.now(as_type='epoch')
        expired_at_state = lib.base.get_state(expired_at / 24 / 60 / 60, args.WARN, args.CRIT, _operator='le')
        state = lib.base.get_worst(state, expired_at_state)

        if args.SEVERITY == 'warn':
            maintenance_state = lib.base.get_state(product.get('has_maintenance', False), True, None, _operator='eq')
        else:
            maintenance_state = lib.base.get_state(product.get('has_maintenance', False), None, True, _operator='eq')
        state = lib.base.get_worst(state, maintenance_state)

        if args.SEVERITY == 'warn':
            locked_state = lib.base.get_state(product.get('is_locked', False), True, None, _operator='eq')
        else:
            locked_state = lib.base.get_state(product.get('is_locked', False), None, True, _operator='eq')
        state = lib.base.get_worst(state, locked_state)

        if args.SEVERITY == 'warn':
            busy_state = lib.base.get_state(product.get('has_operation_in_progress', False), True, None, _operator='eq')
        else:
            busy_state = lib.base.get_state(product.get('has_operation_in_progress', False), None, True, _operator='eq')
        state = lib.base.get_worst(state, busy_state)

        perfdata += lib.base.get_perfdata('{}-busy'.format(product.get('id')), int(product.get('has_operation_in_progress', False)), None, None, None, 0, None)
        perfdata += lib.base.get_perfdata('{}-locked'.format(product.get('id')), int(product.get('is_locked', False)), None, None, None, 0, None)
        perfdata += lib.base.get_perfdata('{}-maintenance'.format(product.get('id')), int(product.get('has_maintenance', False)), None, None, None, 0, None)
        perfdata += lib.base.get_perfdata('{}-size'.format(product.get('id')), product.get('size'), 'B', None, None, 0, None)
        perfdata += lib.base.get_perfdata('{}-storage_reserved'.format(product.get('id')), product.get('storage_reserved'), 'B', None, None, 0, None)

        table_data.append({
            'busy': '{}{}'.format(product.get('has_operation_in_progress', False), lib.base.state2str(busy_state, prefix=' ')),
            'customer_name': product.get('customer_name'),
            'expires_in': '{}{}'.format(lib.human.seconds2human(expired_at), lib.base.state2str(expired_at_state, prefix=' ')),
            'id': product.get('id'),
            'locked': '{}{}'.format(product.get('is_locked', False), lib.base.state2str(locked_state, prefix=' ')),
            'maintenance': '{}{}'.format(product.get('has_maintenance', False), lib.base.state2str(maintenance_state, prefix=' ')),
            'max_slots': product.get('max_slots'),
            'nb_slots': product.get('nb_slots'),
            'size': '{} / {}'.format(lib.human.bytes2human(product.get('storage_reserved')), lib.human.bytes2human(product.get('size'))),
            'tags': ', '.join([i['name'] for i in product.get('tags')]),
        })

    # build the message
    if table_data:
        keys = ['id', 'customer_name', 'tags', 'size', 'nb_slots', 'maintenance', 'locked', 'busy', 'expires_in']
        headers = ['ID', 'Customer', 'Tag', 'Size (alloc/avail)', 'Dev', 'Maint.', 'Locked', 'Busy', 'Expires in']
        # sort table by user tags
        msg += lib.base.get_table(sorted(table_data, key=lambda d: d['tags']) , keys, header=headers)

    if state == STATE_CRIT:
        msg = 'There are critical errors.\n\n' + msg
    elif state == STATE_WARN:
        msg = 'There are warnings.\n\n' + msg
    else:
        msg = 'Everything is ok.\n\n' + msg

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

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