#!/usr/bin/python3

"""
Send alerts if configured to do so
"""

import os
from glob import glob
import configuration
import requests
import argparse

def send_alert (data):

	cfg = configuration.read()

	try:

		url = cfg["webhooks"]["alert"]["url"]

	except KeyError:
		print("Alerts endpoint not configured")
		exit(1)

	authkey = os.environ["GITLAB_ALERTS_AUTHKEY"] if "GITLAB_ALERTS_AUTHKEY" in os.environ else cfg["webhooks"]["alert"]["authkey"]

	headers = {
		"Authorization": "Bearer " + authkey
	}

	requests.post(url, headers=headers, json=data)


if __name__ == '__main__':

	ap = argparse.ArgumentParser()
	ap.add_argument("-t", "--title", required=True, default=None, help="The title of the incident.")
	ap.add_argument("-d", "--description", required=False, default=None, help="A high-level summary of the problem.")
	ap.add_argument("-s", "--service", required=False, default=None, help="The affected service.")
	ap.add_argument("-l", "--severity", required=False, default="critical", help="The severity of the alert. Must be one of critical, high, medium, low, info, unknown. Default is critical.")
	ap.add_argument("-I", "--stdin", required=False, default=None, help="Contents of standard input")
	ap.add_argument("-O", "--stdout", required=False, default=None, help="Contents of standard output")
	ap.add_argument("-E", "--stderr", required=False, default=None, help="Contents of standard error")


	args = vars(ap.parse_args())

	data = {
		"title": args["title"],
		"description": args["description"],
		"service": args["service"],
		"hosts": os.environ["HOST"],
		"severity": args["severity"],
		"input": args["stdin"],
		"output": args["stdout"],
		"error": args["stderr"]
	}

	send_alert(data)

	print("Done")
