#!/usr/lib64/linuxfabrik-monitoring-plugins/venv/bin/python
# -*- 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.url
from lib.globals import STATE_OK, STATE_UNKNOWN

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

DESCRIPTION = """Event Plugin: Changes the security level for a zone at Cloudflare to
"under_attack" if the state of the service, from which this event plugin was called, changes
to CRITICAL (even in SOFT state). Changes it back to "medium" when the state is OK. In "Under
Attack Mode", Cloudflare displays a 5 second delay when a visitor opens the website. This is
useful, for example, when the Apache httpd status check reports overuse."""

TIMEOUT = 8  # seconds


def parse_args():
    """Parse command line arguments using argparse."""
    parser = argparse.ArgumentParser(
        description=DESCRIPTION,
        epilog=lib.args.epilog(__file__, section='event-plugins'),
        formatter_class=lib.args.HelpFormatter,
    )

    parser.add_argument(
        '-V',
        '--version',
        action='version',
        version=f'%(prog)s: v{__version__} by {__author__}',
    )

    parser.add_argument(
        '--key',
        help='Cloudflare API key.',
        dest='KEY',
        required=True,
    )

    parser.add_argument(
        '--servicestate',
        help='The current state of the service.',
        dest='SERVICE_STATE',
        choices=[
            'CRITICAL',
            'OK',
            'UNKNOWN',
            'WARNING',
        ],
        required=True,
    )

    parser.add_argument(
        '--username',
        help='Cloudflare API username (email address).',
        dest='USERNAME',
        required=True,
    )

    parser.add_argument(
        '--zone-id',
        help='Cloudflare API zone identifier '
        '(from Cloudflare Portal > Home > choose your site > Overview). '
        'Can be specified multiple times.',
        action='append',
        dest='ZONE_ID',
        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)

    # nothing to do for states other than CRITICAL and OK
    if args.SERVICE_STATE == 'CRITICAL':
        security_level = 'under_attack'
    elif args.SERVICE_STATE == 'OK':
        security_level = 'medium'
    else:
        sys.exit(STATE_OK)

    # Cloudflare API:
    # https://developers.cloudflare.com/api/resources/zones/subresources/settings/
    header = {
        'Content-Type': 'application/json',
        'X-Auth-Email': args.USERNAME,
        'X-Auth-Key': args.KEY,
    }
    for zone in args.ZONE_ID:
        url = (
            f'https://api.cloudflare.com/client/v4/zones/{zone}/settings/security_level'
        )
        lib.base.coe(
            lib.url.fetch(
                url,
                header=header,
                data={'value': security_level},
                encoding='serialized-json',
                method='PATCH',
                timeout=TIMEOUT,
            )
        )

    # over and out
    sys.exit(STATE_OK)


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