#! /usr/bin/python3

"""
Analyze "{{ ping_log }}"
"""

import sys
import logging
import time

FILE = "{{ ping_log }}"
TAKE_LAST_N_ATTEMPTS = 10

# NOTE: sync with cron period in roles/copr/backend/tasks/copr-ping.yml
CRON_PERIOD = 30*60
WARN_TIME = 6*60
ERR_TIME = 20*60

EXIT_OK = 0
EXIT_WARN = 1
EXIT_CRITICAL = 2
EXIT_UNKNOWN = 3

logging.basicConfig(
    level=logging.INFO,
    format='%(message)s',
    handlers=[logging.StreamHandler(sys.stdout)],
)

LOG = logging.getLogger()
NOW = int(time.time())


def _main():

    # Get the last log line
    line = ""
    with open(FILE, "r", encoding="utf-8") as file:
        for line in file:
            pass

    values = {
        "start": None,
        "stop": None,
        "exit_status": -1,
        "build_id": 0,
    }

    for value in line.split():
        key, value = value.split('=')
        values[key] = value

    if values["start"] is None or values["stop"] is None or values["exit_status"] == -1:
        LOG.error("some values not set in %s", FILE)
        return EXIT_CRITICAL

    if int(values["exit_status"]) != 0:
        LOG.error("Exit status is %s (non-zero) for build ID %s",
                  values["exit_status"], values["build_id"])
        return EXIT_CRITICAL

    build_id = values["build_id"]
    stop = int(values["stop"])
    start = int(values["start"])
    since_last_stop = NOW - stop
    measured_time = since_last_stop - CRON_PERIOD
    took = int(stop - start)

    if measured_time > ERR_TIME:
        LOG.error("%s seconds since the last successful build, allowed %s seconds",
                  since_last_stop, CRON_PERIOD + ERR_TIME)
        return EXIT_CRITICAL

    if measured_time > WARN_TIME:
        LOG.warning("%s seconds since the last successful build, allowed %s seconds",
                    since_last_stop, CRON_PERIOD + WARN_TIME)
        return EXIT_WARN

    LOG.info("The last build %s for copr-ping succeeded, took %s seconds, "
             "elapsed since the last stop %s seconds", build_id, took,
             since_last_stop)
    return EXIT_OK


if __name__ == "__main__":
    try:
        sys.exit(_main())
    except Exception:  # pylint: disable=broad-except
        LOG.exception("UNKNOWN EXCEPTION")
        sys.exit(EXIT_CRITICAL)
