#!/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.base
import lib.nextcloud
from lib.globals import STATE_OK, STATE_UNKNOWN

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

DESCRIPTION = """Retrieves and displays information about an installed Nextcloud Enterprise subscription,
including license status, expiration date, and supported user count.
Alerts when the subscription is expired or about to expire.
Requires root or sudo."""

DEFAULT_PATH = '/var/www/html/nextcloud'
DEFAULT_TIMEOUT = 8


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(
        '--path',
        help='Local path to the Nextcloud installation, typically the web server document root. '
        'Default: %(default)s',
        dest='PATH',
        default=DEFAULT_PATH,
    )

    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
    success, subscription_key = lib.nextcloud.run_occ(
        args.PATH,
        'config:app:get --output=json support subscription_key',
    )
    if not success:
        lib.base.oao('No enterprise subscription found.', STATE_OK)

    success, last_response = lib.nextcloud.run_occ(
        args.PATH,
        'config:app:get support last_response',
    )
    if not success:
        last_response = {}

    success, user_limit = lib.nextcloud.run_occ(
        args.PATH,
        'config:app:get --output=json support user-limit',
    )
    if not success:
        user_limit = 'not set'
    else:
        user_limit += ' users'

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

    # build the message
    msg += f'Subscr.: {last_response.get("amountOfUsers", "N/A")} users, '
    msg += f'Limit: {user_limit}, '
    msg += f'End date: {last_response.get("endDate", "N/A")}, '
    msg += f'Key: *****{subscription_key[-11:]}, '
    msg += f'Level: {last_response.get("level", "N/A")}'

    msg += '\n'
    msg += f'Subscr. Renewal: {last_response.get("subscriptionRenewal", "N/A")}, '
    msg += (
        f'Count active users only: {last_response.get("onlyCountActiveUsers", "N/A")}, '
    )
    msg += f'Hard User Limit: {last_response.get("hasHardUserLimit", "N/A")}, '
    msg += f'Extended Support: {last_response.get("extendedSupport", "N/A")}, '
    msg += f'Branding: {last_response.get("hasBrandingOption", "N/A")}, '
    msg += f'Branding Plus: {last_response.get("hasBrandingPlusOption", "N/A")}, '
    msg += (
        f'Customization Service: {last_response.get("hasCustomizationService", "N/A")}'
    )

    msg += '\n'
    msg += 'Account Manager: '
    msg += f'{last_response.get("accountManagerInfo", {}).get("name", "N/A")}, '
    msg += f'{last_response.get("accountManagerInfo", {}).get("phone", "N/A")}, '
    msg += f'{last_response.get("accountManagerInfo", {}).get("email", "N/A")}'

    for feature in [
        'groupware',
        'talk',
        'collabora',
        'onlyoffice',
        'outlook',
        'sip_bridge',
    ]:
        table_data.append(
            {
                'feature': feature,
                'hasSubscription': last_response.get(feature, {}).get(
                    'hasSubscription', ''
                ),
                'users': last_response.get(feature, {}).get('users', ''),
                'endDate': last_response.get(feature, {}).get('endDate', ''),
                'mcuOption': last_response.get(feature, {}).get('mcuOption', ''),
                'mcuOptionUsers': last_response.get(feature, {}).get(
                    'mcuOptionUsers', ''
                ),
                'level': last_response.get(feature, {}).get('level', ''),
            }
        )
    msg += '\n\n'
    msg += lib.base.get_table(
        table_data,
        [
            'feature',
            'hasSubscription',
            'users',
            'endDate',
            'mcuOption',
            'mcuOptionUsers',
            'level',
        ],
        header=['', 'hasSubscription', 'users', 'endDate', 'mcu', 'mcuUsers', 'level'],
        strip=False,
    )

    perfdata += lib.base.get_perfdata(
        'user_limit',
        user_limit,
        uom=None,
        warn=None,
        crit=None,
        _min=0,
        _max=last_response.get('amountOfUsers'),
    )

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


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