#!/usr/bin/env python

import sys
import argparse
import socket
import logging


from nova_ha_monitor.config import ConsulComputeConfig
from nova_ha_monitor.config import ConsulHAConfig

from nova_ha_utils import util

CLEAR_ENV = ["http_proxy", "https_proxy", "HTTP_PROXY", "HTTPS_PROXY"]

def get_checks(conf):
    return conf.get_health()

def inc_fails(conf):
    n = conf.get_number_fails()
    conf.set_number_fails(n + 1)
    return (n + 1)

def health_aggregate():
    parser = argparse.ArgumentParser()
    parser.add_argument("-r", "--remote-node", type=str, required=True, help='Compute node name')
    parser.add_argument("-l", "--local-checks", nargs="+", default=[],
                        help='List of checkIDs running on compute node')
    parser.add_argument("-m", "--remote-checks", nargs="+", default=[],
                        help='List of checkIDs remotely checking compute node state')
    parser.add_argument("-t", "--threshold", type=int, default=3,
                        help='Number of failed checks intervals allowed')

    args = parser.parse_args()

    #
    # HA and Compute nodes
    remote_node = args.remote_node
    ha_node = socket.gethostname()

    #
    # FIXME: Externalize to consul as we want to keep this dynamic ?
    local_checks = args.local_checks
    remote_checks = args.remote_checks
    threshold = args.threshold

    util.clear_env(clear_env_vars=CLEAR_ENV)

    ha_conf = ConsulHAConfig(socket.gethostname())
    conf = ConsulComputeConfig(remote_node)

    try:
        all_failed = True
        # Test if all required checks are failing and if yes we mark that node as failed.
        for i in get_checks(conf):
            if i['CheckID'] not in local_checks:
                continue
            if i['Status'] == 'passing':
                all_failed = False
            logging.debug('%s/%s: %s', remote_node, i['CheckID'], i['Status'])

        for i in get_checks(ha_conf):
            if i['CheckID'] not in remote_checks:
                continue
            if i['Status'] == 'passing':
                all_failed = False
            logging.debug('%s/%s: %s', ha_node, i['CheckID'], i['Status'])

        if all_failed:
            # Increase number of faillures whih happened on current node.
            if inc_fails(conf) > threshold:
                conf.set_status_failed(True)
        else:
            conf.set_number_fails(0)

        logging.info("%s:%s fails", remote_node, conf.get_number_fails())

        sys.exit(0)
    except StandardError as err:
        logging.error("Error while performing check. %s", str(err))
        sys.exit(2)

if __name__ == '__main__':
    health_aggregate()
