import sys
import time
import urllib.request, urllib.error, urllib.parse

health_endpoint = 'http://localhost:9089/nevisfido/health'
log_file_path = '/var/opt/nevisfido/default/log/nevisfido.log'

# Calls nevisFIDO's health check endpoint repeatedly to determine whether it is up and running
# Returns True if the service is available or False otherwise
def is_nevisfido_healthy():
    for timeout in [0.1, 2, 4, 8, 16, 30]:
        try:
            time.sleep(timeout)
            response = urllib.request.urlopen(health_endpoint)
            if response.getcode() == 200:
                return True
        except urllib.error.URLError:
            continue
    return False

# Parses the nevisFIDO logs for the last error registered and raises and exception about it.
def raise_last_error_in_log():
    event_buffer = []
    for line in reversed(open(log_file_path).readlines()):
        stripped_line = line.rstrip()
        event_buffer.append(stripped_line)
        if '[main] ERROR' in stripped_line:
            raise Exception('\n'.join(reversed(event_buffer)))
            break
        # Log events (by default) starts with logging the time in the following format: '2019-11-04 12:44:45,071 21512 [main]'
        # but these events can be multi-lined.
        # We check here whether the current line is a start of a new event - in which case we flush the buffer.
        if is_year(stripped_line[:4]):
            event_buffer = []

# This method returns True if the provided string can be parsed to a year (4 digit int), or False otherwise.
def is_year(str):
    try:
        return int(str) > 999 and int(str) < 10000
    except ValueError:
        return False

if is_nevisfido_healthy():
    sys.exit(0)
else:
    raise_last_error_in_log()
    sys.exit(1)