#!/usr/bin/env python3
# SMS via ConiuGo gateway
# -*- encoding: utf-8; py-indent-offset: 4 -*-

# (c) 2024 Heinlein Support GmbH
#          Robert Sander <r.sander@heinlein-support.de>

# This is free software;  you can redistribute it and/or modify it
# under the  terms of the  GNU General Public License  as published by
# the Free Software Foundation in version 2.  check_mk is  distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY;  with-
# out even the implied warranty of  MERCHANTABILITY  or  FITNESS FOR A
# PARTICULAR PURPOSE. See the  GNU General Public License for more de-
# tails. You should have  received  a copy of the  GNU  General Public
# License along with GNU Make; see the file  COPYING.  If  not,  write
# to the Free Software Foundation, Inc., 51 Franklin St,  Fifth Floor,
# Boston, MA 02110-1301 USA.

import requests
import os
import sys
from cmk.notification_plugins import utils
    
def main():
    context = dict([ (var[7:], value)
                      for (var, value) in os.environ.items()
                      if var.startswith("NOTIFY_")])

    if context['CONTACTPAGER'] == "":
        sys.stderr.write("Contact's pager address is empty, not sending anything.\n")
        return 0

    text = get_text(context)

    api_password = context.get("PARAMETER_API_PASSWORD")
    if context.get("PARAMETER_API_PASSWORD_1") == "cmk_postprocessed":
        if context["PARAMETER_API_PASSWORD_2"] == "stored_password":
            api_password = utils.retrieve_from_passwordstore("store " + context["PARAMETER_API_PASSWORD_3_1"])
        if context["PARAMETER_API_PASSWORD_2"] == "explicit_password":
            api_password = context["PARAMETER_API_PASSWORD_3_2"]
    api_user = context["PARAMETER_API_USER"]
    api_url = context["PARAMETER_API_URL"] + "/index.php/http_api/send_sms"

    return send_sms(api_url, api_user, api_password, text, context)

def get_text(context):
    max_len = 160
    message = context['HOSTNAME'] + " "

    notification_type = context["NOTIFICATIONTYPE"]

    # Prepare Default information and Type PROBLEM, RECOVERY
    if context['WHAT'] == 'SERVICE':
        if notification_type in [ "PROBLEM", "RECOVERY" ]:
            message += context['SERVICESTATE'][:2] + " "
            avail_len = max_len - len(message)
            message += context['SERVICEDESC'][:avail_len] + " "
            avail_len = max_len - len(message)
            message += context['SERVICEOUTPUT'][:avail_len]
        else:
            message += context['SERVICEDESC']

    else:
        if notification_type in [ "PROBLEM", "RECOVERY" ]:
            message += "is " + context['HOSTSTATE']

    # Ouput the other State
    if notification_type.startswith("FLAP"):
        if "START" in notification_type:
            message += " Started Flapping"
        else:
            message += " Stopped Flapping"

    elif notification_type.startswith("DOWNTIME"):
        what = notification_type[8:].title()
        message += " Downtime " + what
        message += " " + context['NOTIFICATIONCOMMENT']

    elif notification_type == "ACKNOWLEDGEMENT":
        message += " Acknowledged"
        message += " " + context['NOTIFICATIONCOMMENT']

    elif notification_type == "CUSTOM":
        message += " Custom Notification"
        message += " " + context['NOTIFICATIONCOMMENT']

    return message

def send_sms(api_url, api_user, api_password, text, context):
    resp = requests.get(api_url, params={"login": api_user, "pass": api_password, "to": context['CONTACTPAGER'], "message": text})

    if resp.status_code < 300:
        sys.stdout.write("SMS sucessfully sent")
        return 0
    else:
        sys.stderr.write("%s\n" % resp.content)
        return 2

sys.exit(main())
