#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Create message for HPOpenView
# This notification plugin forwards the notification to the
# local HPOpenView instance
#
# Note: Some paths are still hardcoded here.

import os
import re
import sys


def substitute_context(template, context):
    # First replace all known variables
    for varname, value in context.items():
        template = template.replace('$' + varname + '$', value)

    # Remove the rest of the variables and make them empty
    template = re.sub("\\$[A-Z]+\\$", "", template)
    return template


def main():
    try:
        opcmsg_bin = "/opt/OV/bin/opcmsg"

        # gather all options from env
        context = {
            var[7:]: value  #
            for (var, value) in os.environ.items()
            if var.startswith("NOTIFY_")
        }

        # Severity and message text
        if context["WHAT"] == "HOST":
            msg_t = context["HOSTOUTPUT"]
            severity = 'ok' if context['HOSTSTATEID'] == '0' else 'critical'
        else:
            msg_t = context["SERVICEOUTPUT"]
            state_map = {"0": "normal", "1": "warning", "2": "critical", "3": "warning"}
            try:
                severity = state_map[context["SERVICESTATEID"]]
            except Exception:
                severity = "normal"

        # application
        application = "RWWS4.0"

        # object
        # Wichtig: " escapen
        the_object = context["HOSTNAME"]
        if context["WHAT"] == "SERVICE":
            the_object += ":" + context["SERVICEDESC"]

        # msg_grp
        msg_grp = context['CONTACTNAME']

        # node
        node = context['MONITORING_HOST']

        # Assemble the command
        command = "%s severity=%s application=%s object=\"%s\" msg_grp=\"%s\" msg_t=\"%s\" node=%s" % (
            opcmsg_bin, severity, application, the_object, msg_grp, msg_t, node)

        # Execute the command
        print("executing command", command)
        os.system(command)  # nosec
    except Exception as e:
        sys.stdout.write("ERROR %r" % e)
        sys.exit(1)


main()
