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

import lib.base
import lib.shell
from lib.globals import STATE_CRIT, STATE_OK, STATE_UNKNOWN, STATE_WARN

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

DESCRIPTION = """Checks the status and last result of a Windows Scheduled Task. Alerts when the task
has failed or returned a non-zero exit code."""

DEFAULT_SEVERITY = 'warn'
DEFAULT_STATUS = ['Ready', 'Running']


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(
        '--severity',
        help='Severity when the task is not in the expected status. '
        'Default: %(default)s',
        dest='SEVERITY',
        default=DEFAULT_SEVERITY,
        choices=['warn', 'crit'],
    )

    parser.add_argument(
        '--status',
        help='Expected task status. '
        'Can be specified multiple times. '
        'Default: %(default)s',
        dest='STATUS',
        default=DEFAULT_STATUS,
        action='append',
        choices=['Disabled', 'Queued', 'Ready', 'Running', 'Unknown'],
    )

    parser.add_argument(
        '--task',
        help='Name of the Windows scheduled task to check.',
        dest='TASK',
        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)

    problem_state = STATE_CRIT if args.SEVERITY == 'crit' else STATE_WARN

    # fetch data
    stdout, stderr, retc = lib.base.coe(
        lib.shell.shell_exec('schtasks /query /fo csv /nh')
    )
    if stderr or retc != 0:
        lib.base.cu(stderr)

    reader = csv.reader(stdout.strip().splitlines())
    for row in reader:
        task_name, _next_run_time, status = row
        if task_name == args.TASK:
            if status in args.STATUS:
                lib.base.oao(f'{args.TASK} is {status}', STATE_OK)
            # over and out
            lib.base.oao(
                (f'{args.TASK} is {status}, but supposed to be {args.STATUS}'),
                problem_state,
            )

    lib.base.cu(f'Scheduled Task {args.TASK} not found')


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