#!/usr/bin/python3

import logging
import os
import importlib
import sys
from urllib.parse import quote

import pytest
import requests

test_lib = os.environ.get('UCS_TEST_LIB', 'univention.testing.apptest')
try:
	test_lib = importlib.import_module(os.environ.get('UCS_TEST_LIB', 'univention.testing.apptest'))
except ImportError as e:
	print('Could not import {}. Maybe set $UCS_TEST_LIB'.format(test_lib))
	print(e)
	sys.exit(1)

logger = logging.getLogger(__name__)

alert_config_files = [
	"alert_UNIVENTION_DISK_ROOT.yml",
	"alert_UNIVENTION_DISK_ROOT_WARNING.yml",
	"alert_UNIVENTION_DNS.yml",
	"alert_UNIVENTION_JOINSTATUS.yml",
	"alert_UNIVENTION_KPASSWDD.yml",
	"alert_UNIVENTION_LDAP_AUTH.yml",
	"alert_UNIVENTION_LISTENER_MDB_MAXSIZE_WARNING.yml",
	"alert_UNIVENTION_LISTENER_MDB_MAXSIZE.yml",
	"alert_UNIVENTION_LOAD_WARNING.yml",
	"alert_UNIVENTION_LOAD.yml",
	"alert_UNIVENTION_NMBD.yml",
	"alert_UNIVENTION_NSCD2.yml",
	"alert_UNIVENTION_NSCD.yml",
	"alert_UNIVENTION_NTP_WARNING.yml",
	"alert_UNIVENTION_NTP.yml",
	"alert_UNIVENTION_PACKAGE_STATUS.yml",
	"alert_UNIVENTION_REPLICATION_WARNING.yml",
	"alert_UNIVENTION_REPLICATION.yml",
	"alert_UNIVENTION_SLAPD_MDB_MAXSIZE_WARNING.yml",
	"alert_UNIVENTION_SLAPD_MDB_MAXSIZE.yml",
	"alert_UNIVENTION_SMBD.yml",
	"alert_UNIVENTION_SMTP.yml",
	"alert_UNIVENTION_SSL_WARNING.yml",
	"alert_UNIVENTION_SSL.yml",
	"alert_UNIVENTION_SWAP_WARNING.yml",
	"alert_UNIVENTION_SWAP.yml",
	"alert_UNIVENTION_WINBIND.yml"
]

metrics = [
	"univention_dns_resolveable",
	"univention_ldap_reachable",
	"univention_ntp_offset_seconds",
	"univention_smtp_reachable",
	"univention_ssl_certificate_expiry_seconds",
	"univention_listener_replication_difference",
	"univention_nscd_running",
	"univention_nscd_responding",
	"univention_kpasswdd_running",
	"univention_winbind_secret_ok",
	"univention_smbd_accessible",
	"univention_nmbd_running",
	"univention_join_status",
	"univention_package_status_ok",
	"univention_slapd_mdb_size_used_ratio",
	"univention_listener_mdb_size_used_ratio"
]


@pytest.mark.parametrize("config_file", alert_config_files)
def test_alert_configuration_files(config_file):
	logger.warning("Checking if config file %s exists" % (config_file,))
	path = "/var/lib/univention-appcenter/apps/prometheus/conf/"
	assert open(os.path.join(path, config_file)).read().strip()


@pytest.mark.parametrize("metric", metrics)
def test_metric(metric):
	logger.warning("Checking if metric %s exists in prometheus" % (metric,))
	prom_url = "http://localhost:9090/metrics-prometheus/api/v1/query?query=%s" % (quote(metric),)
	response = requests.get(prom_url)
	response.raise_for_status()
	body = response.json()
	assert body['data']['result'] is not None


if __name__ == '__main__':
	logger.warning("trying to exceute %s" % (__file__,))
	test_lib.run_test_file(__file__)
