#!/usr/bin/python
# encoding: utf-8
# Source from https://www.mattfay.com.au/scripts/check_mk-pushbullet-notifications/
# Plugin location [site-root]/local/share/check_mk/notifications/
# Update notificaiton channel over proxy
# Notify via PushBullet
import os, sys, urllib2, json

# Gather notification data
hostname=os.getenv('NOTIFY_HOSTNAME')
hostalias=os.getenv('NOTIFY_HOSTALIAS')
notification=os.getenv('NOTIFY_NOTIFICATIONTYPE')
if os.getenv('NOTIFY_SERVICEDESC') == '$SERVICEDESC$':
  # Host report
  service='Host'
  output=os.getenv('NOTIFY_HOSTOUTPUT')
  oldstate=os.getenv('NOTIFY_LASTHOSTSTATE')
  newstate=os.getenv('NOTIFY_HOSTSTATE')
else:
  # Service report
  service=os.getenv('NOTIFY_SERVICEDESC')
  output=os.getenv('NOTIFY_SERVICEOUTPUT')
  oldstate=os.getenv('NOTIFY_LASTSERVICESTATE')
  newstate=os.getenv('NOTIFY_SERVICESTATE')

# Configure push auth, details, and format - change these
push_channel=[channel name]
push_token=[token key from pushbullet]
push_title='[OMD] '+hostalias.upper()+' '+notification
push_body=service+' '+oldstate+' -> '+output+' ('+hostname+')'

# Set up request
push_url='https://api.pushbullet.com/v2/pushes'
push_header={'Access-Token' : push_token,
             'Content-Type' : 'application/json'}
push_data=json.dumps({'type'        : 'note',
                      'channel_tag' : push_channel,
                      'title'       : push_title,
                      'body'        : push_body})

# Send to PushBullet API
try:
  req=urllib2.Request(push_url,headers=push_header,data=push_data)
  proxy = urllib2.ProxyHandler({'https': 'http://squid-proxy:3128'})
  opener = urllib2.build_opener(proxy)
  urllib2.install_opener(opener)
  urllib2.urlopen(req)
except urllib2.HTTPError as e:
  error_message = e.read()
  print error_message
