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

# (c) 2018 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 sys
import xml.etree.ElementTree as ET
from cmk.notification_plugins import utils

api_url = "https://url.ecall.ch/api/sms"

def main():
    context = utils.collect_context()

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

    text    = get_text(context)

    username = context["PARAMETER_USERNAME"]
    password = context.get("PARAMETER_PASSWORD")
    if context.get("PARAMETER_PASSWORD_1") == "cmk_postprocessed":
        if context["PARAMETER_PASSWORD_2"] == "stored_password":
            password = utils.retrieve_from_passwordstore("store " + context["PARAMETER_PASSWORD_3_1"])
        if context["PARAMETER_PASSWORD_2"] == "explicit_password":
            password = context["PARAMETER_PASSWORD_3_2"]

    return send_sms(username, 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']

    # Output 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(username, password, text, context):
    data = {
        # 'CallBack': os.environ.get('OMD_SITE', 'checkMK'),
        'UserName': username,
        'Password': password,
        'Address': context['CONTACTPAGER'].replace(" ", ""),
        'Message': text
    }

    resp = requests.post(api_url, data=data)
    if resp.text.startswith('<Result '):
        root = ET.fromstring(resp.text.encode('utf-8'))
    else:
        root = ET.fromstring('<empty />')

    responsedata = {
        'AdditionalInfo': None,
        'ResultCode': None,
        'ResultText': "",
    }

    if root.tag == '{http://schemas.datacontract.org/2004/07/eCallHttp.Models}Result':
        for child in root:
            for key in responsedata.keys():
                if child.tag.endswith(key):
                    responsedata[key] = child.text
                    
    if resp.status_code == 200:
        if responsedata['ResultCode'] == '0':
            sys.stdout.write("SMS sucessfully sent\n")
            return 0
        
    sys.stderr.write("%s" % responsedata)
    return 2

sys.exit(main())
