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

import lib.base  # pylint: disable=C0413
import lib.qts  # pylint: disable=C0413
import lib.txt  # pylint: disable=C0413
import lib.url  # pylint: disable=C0413
import lib.version  # pylint: disable=C0413
from lib.globals import (STATE_OK, STATE_UNKNOWN,  # pylint: disable=C0413
                          STATE_WARN)

try:
    import xmltodict
except ImportError as e:
    print('Python module "xmltodict" is not installed.')
    sys.exit(STATE_UNKNOWN)


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

DESCRIPTION = 'This plugin lets you track if server updates are available.'

DEFAULT_INSECURE = False
DEFAULT_NO_PROXY = False
DEFAULT_TIMEOUT = 6
DEFAULT_USERNAME = 'admin'


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(
        '--always-ok',
        help='Always returns OK.',
        dest='ALWAYS_OK',
        action='store_true',
        default=False,
    )

    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(
        '--password',
        help='QTS Password.',
        dest='PASSWORD',
        required=True,
    )

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

    parser.add_argument(
        '--url',
        help='QTS-based Appliance URL, for example https://192.168.1.1:8080.',
        dest='URL',
        required=True,
    )

    parser.add_argument(
        '--username',
        help='QTS User. '
             'Default: %(default)s',
        dest='USERNAME',
        default=DEFAULT_USERNAME,
    )

    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)

    auth_sid = lib.base.coe(lib.qts.get_auth_sid(args))

    # get system information
    url = '{}/cgi-bin/management/manaRequest.cgi?subfunc=sysinfo&hd=no&multicpu=1&sid={}'.format(
        args.URL,
        auth_sid,
    )
    result = lib.base.coe(
        lib.url.fetch(url, insecure=args.INSECURE, no_proxy=args.NO_PROXY, timeout=args.TIMEOUT)
    )
    data = xmltodict.parse(result)['QDocRoot']
    if data['authPassed'] == '0':
        lib.base.cu('Insufficient permissions.')

    installed_version = data['firmware']['version']
    installed_number = data['firmware']['number']
    installed_build = data['firmware']['build']

    # check for updates
    url = '{}/cgi-bin/sys/sysRequest.cgi?subfunc=firm_update&sid={}'.format(args.URL, auth_sid)
    result = lib.base.coe(
        lib.url.fetch(
            url,
            data=data,
            insecure=args.INSECURE,
            no_proxy=args.NO_PROXY,
            timeout=args.TIMEOUT,
        )
    )
    xmldict = xmltodict.parse(result)['QDocRoot']
    if 'newVersion' in xmldict['func']['ownContent']:
        # versions up to 5.0.1
        latest_version = xmldict['func']['ownContent']['newVersion']
    elif 'version' in xmldict['firmware']:
        # version 5.0.1+
        latest_version = xmldict['firmware']['version']
    else:
        lib.base.cu('Version information cannot be determined.')

    if latest_version == 'none':
        latest_version = None
    elif latest_version == 'error' or len(latest_version) == 0:
        lib.base.cu('Got an error from the QNAP API.')

    # build the message
    if lib.version.version('.'.join(installed_version)) >= lib.version.version(latest_version):
        lib.base.oao(
            'QTS v{}.{} Build {} is up to date'.format(
                installed_version,
                installed_number,
                installed_build,
            ),
            STATE_OK,
        )
    lib.base.oao(
        'QTS v{}.{} Build {} installed, QTS v{} available'.format(
            installed_version,
            installed_number,
            installed_build,
            latest_version,
        ),
        STATE_WARN,
        always_ok=args.ALWAYS_OK,
    )


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