#!/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 datetime
import sys

import lib.args
import lib.base
import lib.time
import lib.txt
from lib.globals import STATE_CRIT, STATE_OK, STATE_UNKNOWN, STATE_WARN

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

DESCRIPTION = """Counts down to one or more user-defined expiration dates, such as certificate renewals,
contract deadlines, or license expirations. Alerts when the remaining days fall below
the configured warning or critical thresholds. Each item can have its own thresholds.
Past dates are reported as expired."""

DEFAULT_WARN = 50  # days
DEFAULT_CRIT = 30  # days


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

    parser.add_argument(
        '--input',
        help='Countdown item in the format "Display Name, YYYY-MM-DD, warn, crit". '
        'Can be specified multiple times. '
        'Example: `--input "Supermicro SYS1, 2025-01-10, 50, 30"`.',
        dest='INPUT',
        type=lib.args.csv,
        required=True,
        action='append',
    )

    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)

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

    try:
        # ['Supermicro SYS1, 2022-01-10, 50, None', 'Contract XMPL.COM, 2021-12-24, 50, 30']
        for line in args.INPUT:
            item, expiration_date, warn, crit = line

            expiration_date = datetime.datetime.strptime(expiration_date, '%Y-%m-%d')
            today = lib.time.now(as_type='datetime')
            delta = expiration_date - today
            delta = int(delta.days) + 1

            if crit.lower() != 'none' and delta < int(crit):
                line_state = STATE_CRIT
            elif warn.lower() != 'none' and delta < int(warn):
                line_state = STATE_WARN
            else:
                line_state = STATE_OK

            if delta > 0:

                # build the message
                msg += f'* {item} expires in {delta} {lib.txt.pluralize("day", delta)} (thresholds {warn}/{crit}){lib.base.state2str(line_state, prefix=" ")}\n'
            elif delta == 0:
                msg += f'* {item} expires today{lib.base.state2str(line_state, prefix=" ")}\n'
            else:
                msg += f'* {item} expired {abs(delta)} {lib.txt.pluralize("day", abs(delta))} ago{lib.base.state2str(line_state, prefix=" ")}\n'

            state = lib.base.get_worst(line_state, state)

        if state == STATE_CRIT:
            msg = 'There are one or more criticals.\n' + msg
        elif state == STATE_WARN:
            msg = 'There are one or more warnings.\n' + msg
        else:
            msg = 'Everything is ok.\n' + msg

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

    except Exception:
        lib.base.cu(
            'Something seems to be wrong with the input parameter format or its timestamps'
        )


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