#!/usr/bin/python3

import requests
import getpass
import json
import os

from urllib.parse import urljoin
from datetime import datetime

from constants import L7_ALERTS, L7_ALERTS_EXP
from deploy_monitoring import deploy_monitoring_content
from settings import settings_flap_detector, settings_aggr, settings_juggler_hosts

import active_checks
import passive_checks

OAUTH_TOKEN = os.environ['OAUTH_NANNY']


monitoring_yandex_tld = {
    "deploy_monitoring": { "user": L7_ALERTS, "timeout": 1800 },
    "active_checks": {
        "health_check": {
            "url": "/any_url",
            "code": 302,
        }
    },
    "passive_checks": {"check_enddate_certificate": {}, "push_client": {}, "check_space": {}, "check_tun": {},},
    "juggler_tags": ["yandex.ru"],
}


monitoring_yandex_exp_tld = {
    "deploy_monitoring": { "user": L7_ALERTS_EXP, "timeout": 1800 },
    "active_checks": {
        "health_check": {
            "url": "/any_url",
            "code": 302,
        }
    },
    "passive_checks": {"check_enddate_certificate": {}, "push_client": {"args": ["-l", "65000000000"],}, "check_space": {}, "check_tun": {},},
    "juggler_tags": ["yandex.ru"],
}


monitoring_yaru = {
    "deploy_monitoring": { "user": L7_ALERTS, "timeout": 1800 },
    "active_checks": {
        "health_check": {
            "url": "/any_url",
            "code": 404,
        }
    },
    "passive_checks": {"check_enddate_certificate": {}, "push_client": {}, "check_space": {},},
    "juggler_tags": ["ya.ru"],
}


monitoring_any = {
    "deploy_monitoring": { "user": L7_ALERTS, "timeout": 1800 },
    "active_checks": {
        "health_check": {
            "url": "/any_url",
            "code": 404,
        }
    },
    "passive_checks": {"check_enddate_certificate": {}, "push_client": {}, "check_space": {},},
    "juggler_tags": ["any.yandex.ru"],
}


services = {
    "balancer_l7leveler_kubr_man": monitoring_yandex_tld,
    "balancer_l7leveler_kubr_sas": monitoring_yandex_tld,
    "balancer_l7leveler_kubr_vla": monitoring_yandex_tld,

    "balancer_l7leveler_kubr_vla_exp_amd": monitoring_yandex_exp_tld,
    "balancer_l7leveler_kubr_vla_exp_new": monitoring_yandex_exp_tld,
    "balancer_l7leveler_kubr_vla_experiment": monitoring_yandex_exp_tld,

    "balancer_l7leveler_yaru_man": monitoring_yaru,
    "balancer_l7leveler_yaru_sas": monitoring_yaru,
    "balancer_l7leveler_yaru_vla": monitoring_yaru,

    "production_balancer_any_man": monitoring_any,
    "production_balancer_any_sas": monitoring_any,
    "production_balancer_any_vla": monitoring_any,
}

def main():
    session = requests.Session()
    session.headers['Authorization'] = 'OAuth {}'.format(OAUTH_TOKEN)
    session.headers['Content-Type'] = 'application/json'

    for service in services:
        service_url = 'https://nanny.yandex-team.ru/v2/services/{service}/info_attrs/'.format(service=service)
        curr_info_attrs = session.get(service_url).json()

        snapshot_id = curr_info_attrs["_id"]
        info_attrs = curr_info_attrs["content"]

        if "deploy_monitoring" not in info_attrs["monitoring_settings"]:
            info_attrs["monitoring_settings"]["deploy_monitoring"] = {}

        if "juggler_settings" not in info_attrs["monitoring_settings"]:
            info_attrs["monitoring_settings"]["juggler_settings"] = {}

        #
        # Deploy monitoring
        #

        info_attrs["monitoring_settings"]["deploy_monitoring"]["content"] = deploy_monitoring_content(**services[service]["deploy_monitoring"])
        info_attrs["monitoring_settings"]["deploy_monitoring"]["is_enabled"] = True

        #
        # End Deploy monitoring
        #

        if "content" not in info_attrs["monitoring_settings"]["juggler_settings"]:
            info_attrs["monitoring_settings"]["juggler_settings"]["content"] = {
                "instance_resolve_type": "NANNY",
                "juggler_hosts": settings_juggler_hosts(service),
                "active_checks": [{"checks": [], "flap_detector": {}, "module": {}, "passive_checks": [], "per_auto_tags": []}],
                "juggler_tags": services[service]["juggler_tags"],
            }
        info_attrs["monitoring_settings"]["juggler_settings"]["is_enabled"] = True

        juggler_host = info_attrs["monitoring_settings"]["juggler_settings"]["content"]["juggler_hosts"][0]["name"]

        #
        # Active checks
        #
        inst_active_checks = []
        for active_check in services[service]["active_checks"]:
            fn = method_to_call = getattr(active_checks, "active_{0}".format(active_check))
            inst_active_checks.append(fn(juggler_host, services[service]["deploy_monitoring"]["user"], **services[service]["active_checks"][active_check]))
        info_attrs["monitoring_settings"]["juggler_settings"]["content"]["active_checks"][0]["checks"] = inst_active_checks

        #
        # End Active checks
        #

        #
        # Passive checks
        #
        inst_passive_checks = []
        for passive_check in services[service]["passive_checks"]:
            fn = method_to_call = getattr(passive_checks, "passive_{0}".format(passive_check))
            inst_passive_checks.append(fn(juggler_host, services[service]["deploy_monitoring"]["user"], **services[service]["passive_checks"][passive_check]))
        info_attrs["monitoring_settings"]["juggler_settings"]["content"]["active_checks"][0]["passive_checks"] = inst_passive_checks

        #
        # End Passive checks
        #

        #
        # Flap detector and Aggregated settings
        #

        info_attrs["monitoring_settings"]["juggler_settings"]["content"]["active_checks"][0]["flap_detector"] = settings_flap_detector()
        info_attrs["monitoring_settings"]["juggler_settings"]["content"]["active_checks"][0]["module"] = settings_aggr()

        r = session.put(service_url, json={
            'snapshot_id': snapshot_id,
            'content': info_attrs,
            'comment': 'Updated by {0} on {1}'.format(getpass.getuser(), datetime.now().strftime('%Y-%m-%d %H:%M:%S')),
        })
        if r.status_code != 200:
            print(r.content)
        else:
            print("+ service {0}: OK".format(service))

main()

