#!/usr/bin/env python3

"""
Nagios plugin to check that Zephyr mirror forwarding is running.

This script just checks the contents of a file. The forwarding test
itself lives in api/integrations/zephyr/check-mirroring and should be
run out of cron.

See puppet/zulip_ops/files/cron.d/zephyr-mirror for the crontab details.
"""
import os
import time
from typing import Dict

RESULTS_FILE = "/var/lib/nagios_state/check-mirroring-results"

states: Dict[str, int] = {
    "OK": 0,
    "WARNING": 1,
    "CRITICAL": 2,
    "UNKNOWN": 3,
}


def report(state: str, data: str, last_check: float) -> None:
    print(
        "{}: Last test run completed at {}\n{}".format(
            state, time.strftime("%Y-%m-%d %H:%M %Z", time.gmtime(last_check)), data
        )
    )
    exit(states[state])


with open(RESULTS_FILE) as f:
    data = f.read().strip()
if data.split("\n")[-1].strip() == "0":
    state = "OK"
else:
    state = "CRITICAL"

last_check = os.stat(RESULTS_FILE).st_mtime
time_since_last_check = time.time() - last_check
if time_since_last_check > 60 * 5:
    state = "UNKNOWN"
    data = "Results file is stale"

report(state, data, last_check)
