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

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

DESCRIPTION = """Monitors Rocket.Chat server statistics via the API, including total users, active
users, online users, channels, messages, uploads, and file storage usage. Requires
a user with "view-statistics" permission."""

DEFAULT_INSECURE = False
DEFAULT_NO_PROXY = False
DEFAULT_TIMEOUT = 3
DEFAULT_URL = 'http://localhost:3000/api/v1'
DEFAULT_USERNAME = 'rocket-stats'


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(
        '--insecure',
        help=lib.args.help('--insecure'),
        dest='INSECURE',
        action='store_true',
        default=DEFAULT_INSECURE,
    )

    parser.add_argument(
        '--no-proxy',
        help=lib.args.help('--no-proxy'),
        dest='NO_PROXY',
        action='store_true',
        default=DEFAULT_NO_PROXY,
    )

    parser.add_argument(
        '-p',
        '--password',
        help='Rocket.Chat API password.',
        dest='PASSWORD',
        required=True,
    )

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

    parser.add_argument(
        '--url',
        help='Rocket.Chat API URL. Default: %(default)s',
        dest='URL',
        default=DEFAULT_URL,
    )

    parser.add_argument(
        '--username',
        help='Rocket.Chat API username. Default: %(default)s',
        dest='USERNAME',
        default=DEFAULT_USERNAME,
        required=True,
    )

    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
    credentials = lib.base.coe(
        lib.rocket.get_token(
            args.URL,
            args.USERNAME,
            args.PASSWORD,
            insecure=args.INSECURE,
            no_proxy=args.NO_PROXY,
            timeout=args.TIMEOUT,
        )
    )
    auth_token, user_id = credentials.split(':')
    result = lib.base.coe(
        lib.rocket.get_stats(
            args.URL,
            auth_token,
            user_id,
            insecure=args.INSECURE,
            no_proxy=args.NO_PROXY,
            timeout=args.TIMEOUT,
        )
    )

    # init some vars
    msg = ''
    perfdata = ''
    state = STATE_OK

    # build a compact multiline message with the most important info first
    msg += (
        f'{result.get("onlineUsers", "n/a")}'
        f'/{result.get("totalUsers", "n/a")} users online,'
        f' {lib.human.number2human(result.get("totalMessages", 0))}'
        f' {lib.txt.pluralize("msg", result.get("totalMessages", 0))},'
        f' {lib.human.number2human(result.get("uploadsTotal", 0))}'
        f' {lib.txt.pluralize("upload", result.get("uploadsTotal", 0))},'
        f' {lib.human.bytes2human(result.get("uploadsTotalSize", 0))}'
        f' upload total size,'
        f' v{result.get("version", "n/a")}'
    )

    # no checks here, just for your information
    msg += (
        f'\n* Users: {result.get("totalUsers", "n/a")} total'
        f' ({result.get("onlineUsers", "n/a")} online,'
        f' {result.get("busyUsers", "n/a")} busy,'
        f' {result.get("awayUsers", "n/a")} away,'
        f' {result.get("offlineUsers", "n/a")} offline)'
    )


    # build the message
    msg += (
        f'\n* Types and Distribution:'
        f' {result.get("totalConnectedUsers", "n/a")}'
        f' of {result.get("activeUsers", "n/a")}'
        f' activated'
        f' {lib.txt.pluralize("user", result.get("activeUsers", 0))}'
        f' online,'
        f' {result.get("activeGuests", "n/a")}'
        f' activated'
        f' {lib.txt.pluralize("guest", result.get("activeGuests", 0))},'
        f' {result.get("nonActiveUsers", "n/a")}'
        f' deactivated'
        f' {lib.txt.pluralize("user", result.get("nonActiveUsers", 0))},'
        f' {result.get("appUsers", "n/a")}'
        f' Rocket.Chat app'
        f' {lib.txt.pluralize("user", result.get("appUsers", 0))}'
    )

    msg += (
        f'\n* Total Uploads:'
        f' {result.get("uploadsTotal", "n/a")},'
        f' {lib.human.bytes2human(result.get("uploadsTotalSize", 0))}'
        f' size'
    )

    msg += (
        f'\n* Total Rooms:'
        f' {result.get("totalRooms", "n/a")}'
        f' ({result.get("totalChannels", "n/a")}'
        f' {lib.txt.pluralize("channel", result.get("totalChannels", 0))},'
        f' {result.get("totalPrivateGroups", "n/a")}'
        f' private'
        f' {lib.txt.pluralize("group", result.get("totalPrivateGroups", 0))},'
        f' {result.get("totalDirect", "n/a")}'
        f' direct msg'
        f' {lib.txt.pluralize("room", result.get("totalDirect", 0))},'
        f' {result.get("totalDiscussions", "n/a")}'
        f' {lib.txt.pluralize("discussion", result.get("totalDiscussions", 0))},'
        f' {result.get("totalLivechat", "n/a")}'
        f' omnichannel'
        f' {lib.txt.pluralize("room", result.get("totalLivechat", 0))})'
    )

    msg += (
        f'\n* Total Messages:'
        f' {lib.human.number2human(result.get("totalMessages", 0))}'
        f' ({result.get("totalThreads", "n/a")}'
        f' {lib.txt.pluralize("thread", result.get("totalThreads", 0))},'
        f' {result.get("totalChannelMessages", "n/a")}'
        f' in channels,'
        f' {lib.human.number2human(result.get("totalPrivateGroupMessages", 0))}'
        f' in priv groups,'
        f' {lib.human.number2human(result.get("totalDirectMessages", 0))}'
        f' in direct msg,'
        f' {lib.human.number2human(result.get("totalLivechatMessages", 0))}'
        f' in omnichannel)'
    )

    perfdata += lib.base.get_perfdata(
        'rc_totalUsers',
        result.get('totalUsers', 0),
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'rc_onlineUsers',
        result.get('onlineUsers', 0),
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'rc_busyUsers',
        result.get('busyUsers', 0),
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'rc_awayUsers',
        result.get('awayUsers', 0),
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'rc_offlineUsers',
        result.get('offlineUsers', 0),
        _min=0,
    )

    perfdata += lib.base.get_perfdata(
        'rc_totalConnectedUsers',
        result.get('totalConnectedUsers', 0),
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'rc_activeUsers',
        result.get('activeUsers', 0),
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'rc_activeGuests',
        result.get('activeGuests', 0),
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'rc_nonActiveUsers',
        result.get('nonActiveUsers', 0),
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'rc_appUsers',
        result.get('appUsers', 0),
        _min=0,
    )

    perfdata += lib.base.get_perfdata(
        'rc_uploadsTotal',
        result.get('uploadsTotal', 0),
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'rc_uploadsTotalSize',
        result.get('uploadsTotalSize', 0),
        uom='B',
        _min=0,
    )

    perfdata += lib.base.get_perfdata(
        'rc_totalRooms',
        result.get('totalRooms', 0),
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'rc_totalChannels',
        result.get('totalChannels', 0),
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'rc_totalPrivateGroups',
        result.get('totalPrivateGroups', 0),
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'rc_totalDirect',
        result.get('totalDirect', 0),
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'rc_totalDiscussions',
        result.get('totalDiscussions', 0),
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'rc_totalLivechat',
        result.get('totalLivechat', 0),
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'rc_totalMessages',
        result.get('totalMessages', 0),
        _min=0,
    )

    perfdata += lib.base.get_perfdata(
        'rc_totalThreads',
        result.get('totalThreads', 0),
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'rc_totalChannelMessages',
        result.get('totalChannelMessages', 0),
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'rc_totalPrivateGroupMessages',
        result.get('totalPrivateGroupMessages', 0),
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'rc_totalDirectMessages',
        result.get('totalDirectMessages', 0),
        _min=0,
    )
    perfdata += lib.base.get_perfdata(
        'rc_totalLivechatMessages',
        result.get('totalLivechatMessages', 0),
        _min=0,
    )

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


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