#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2014             mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk 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.

# Send SMS via MultiTech SMS-Gateway # encoding: utf-8
#
# This notification script can be put below share/check_mk/notifications. It sends
# SMS via a MultiTech SMS-Gateway
# (http://www.multitech.com/en_US/PRODUCTS/Families/MultiModemiSMS/)
# Please add your personal configuration directly in this
# script. The target phone number is take from the contact's pager address.
# You can override this by specifying it as a parameter
#
# Some hints for setup of the MultiTech SMS-Gateway:
#
# * Please use at least Firmware Version 1.51.9 earlier versions did cause much
#   trouble. The devices are not yet delivered with this version, so an upgrade is
#   required. You get SF100-u-v1.51.9-16Jan2013.bin.zip e. g. at
#   https://shop.netways.de/attachment.php?id_attachment=64
#
# * Deactivate the PIN of the SIM card. This can be done most easy by inserting
#   the SIM into a mobile phone.
#
# * By default, the device has IP 192.168.2.1, user admin, password admin.
#   You can change these in the admin interface by browser (http).
#
# * Look into the status information in the web interface to make sure, the
#   SIM card is displayed as enabled there.
#   If not: Make sure you did insert the SIM card with contacts to the bottom,
#   and the cut off corner to the front right.
#
# * Under
#     Administration > Admin Access > Allowed Networks
#   you can restrict access to the device. Make sure, the IPs of the sending
#   Check_MK machines are included there.
#
# * Under
#     SMS Services > Send API
#   enable HTTP Status, set port to 80
#
# * Under
#     SMS Services > International Number
#   clear the check box "Disable International Number"
#
# * Under
#     SMS Services > Send SMS Users
#   create a user for Check_MK. This one needs to be entered below.
#   Make sure you choose a password, which is not longer than 8 characters.
#   On the device it is possible to set a longer password, but authentication
#   with it is impossible!! :-(
#
# * Do not forget to go to the "Save & Restart" tab and click "save" there.
#   This writes your changes into the flash memory of the device. Otherwise
#   they will be lost on next reboot.
#


import sys, os, urllib

# This does not need to be changed
to       = os.environ.get("NOTIFY_CONTACTPAGER")
fromname = "Check_MK"
user     = "nagios"
passwd   = "test123"
url      = "http://isms.example.com/sendmsg?"


if len(sys.argv) > 1:
    to = sys.argv[1]

if not to:
    sys.stderr.write("NOTIFY_CONTACTPAGER is not set.\n")
    sys.exit(1)


max_len = 160
message = os.environ['NOTIFY_HOSTNAME'] + " "

if os.environ['NOTIFY_WHAT'] == 'SERVICE':
    message += os.environ['NOTIFY_SERVICESTATE'][:2] + " "
    avail_len = max_len - len(message)
    message += os.environ['NOTIFY_SERVICEDESC'][:avail_len] + " "
    avail_len = max_len - len(message)
    message += os.environ['NOTIFY_SERVICEOUTPUT'][:avail_len]

else:
    message += "is " + os.environ['NOTIFY_HOSTSTATE']

# constructing a url like
# http://isms.example.com/sendmsg?user=nagios&passwd=test123&cat=1&to=017012345678&text=sample' 
url += urllib.urlencode([ 
   ( "user", user ),
   ( "passwd", passwd ),
   ( "cat", "1" ),
   ( "to", to ),
   ( "text", message )
])


try:
    handle = urllib.urlopen(url)
    response = handle.read().strip()
    sys.stdout.write("%s\n" % response)
    if response.startswith("ID:"):
        sys.stdout.write("Successfully sent SMS to %s\n" % to)
    else:
        sys.stderr.write("Error sending SMS to %s: %s\n" % (to, response))
        sys.stderr.write("URL was %s\n" % url)
except Exception, e:
    sys.stderr.write("Error sending SMS to %s. Exception: %s%s\n" % e)

