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

import lib.base  # pylint: disable=C0413
import lib.cache  # pylint: disable=C0413
import lib.shell  # pylint: disable=C0413
import lib.time  # 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)

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

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

DEFAULT_CACHE_EXPIRE = 24 # hours


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

    parser.add_argument(
        '--cache-expire',
        help='The amount of time after which the update check cache expires, in hours. '
             'Default: %(default)s',
        dest='CACHE_EXPIRE',
        type=int,
        default=DEFAULT_CACHE_EXPIRE,
    )

    return parser.parse_args()


def get_installed_version():
    success, result = lib.shell.shell_exec('mydumper --version')
    if not success:
        return ''
    stdout, stderr, retc = result
    stdout = stdout.strip()
    # where to find the version number in output?
    version_regex = r'mydumper(.*?),'
    try:
        stdout = re.search(version_regex, stdout)
        return stdout.group(1).strip()
    except:
        return ''


def get_latest_version(expire):
    # get version online, but first from cache
    latest_version = lib.cache.get('mydumper-version')
    if latest_version:
        return (True, latest_version)

    # nothing found in cache, get the latest version from github
    success, latest_version = lib.url.get_latest_version_from_github('mydumper', 'mydumper')
    if not success:
        return (success, latest_version)

    lib.cache.set('mydumper-version', latest_version, lib.time.now() + expire)
    return (True, latest_version)


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)

    installed_version = get_installed_version()
    if not installed_version:
        lib.base.cu('mydumper/myloader not found.')

    latest_version = lib.base.coe(get_latest_version(args.CACHE_EXPIRE*60*60))
    perfdata = lib.base.get_perfdata('mydumper-version', lib.version.version2float(installed_version), None, None, None, 0, None) # pylint: disable=C0301

    if lib.version.version(installed_version) >= lib.version.version(latest_version):
        lib.base.oao(
            'mydumper/myloader {} is up to date'.format(installed_version),
            STATE_OK,
            perfdata,
        )

    # over and out
    lib.base.oao(
        'mydumper/myloader {} installed, mydumper/myloader {} available'.format(
            installed_version,
            latest_version,
        ),
        STATE_WARN,
        perfdata,
        always_ok=args.ALWAYS_OK,
    )


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