#!/usr/bin/env python
#
# mike@nerdkits.com
# April 22, 2010
#
# (This is a trivial little script.  
#  Uncopyrighted / Released as public domain.)

####################################################################
# Set these to your Notifo service profider username and 
# API key.  (If confused, note that API key != password.)

NOTIFO_USER = 'YOUR_NOTIFO_USERNAME_HERE'
NOTIFO_KEY = 'YOUR_NOTIFO_API_KEY_GOES_HERE'

####################################################################

import base64
import optparse
import sys
import urllib
import urllib2
try:
  import json
except ImportError:
  import simplejson as json


def post_with_auth(url, data):
  raw = '%s:%s' % (NOTIFO_USER, NOTIFO_KEY)
  auth = 'Basic %s' % base64.b64encode(raw).strip()
  auth_header = 'Authorization'

  req = urllib2.Request(url=url, data=data)
  req.add_header(auth_header, auth)
  
  try:
    return urllib2.urlopen(req).read()
  except urllib2.HTTPError, e:
    return e.read()

def send_notification(to, msg, title=None, uri=None):
  datadict = {'to': to, 'msg': msg}
  if title:
    datadict['title'] = title
  if uri:
    datadict['uri'] = uri

  data = urllib.urlencode(datadict)
  return post_with_auth('https://api.notifo.com/v1/send_notification', data)

def subscribe_user(username):
  datadict = {'username': username}
  data = urllib.urlencode(datadict)
  return post_with_auth('https://api.notifo.com/v1/subscribe_user', data)

def main():
  parser = optparse.OptionParser(usage="Usage: %prog [options] username1 username2 ...")
  parser.set_defaults(mode='send_notification')
  parser.add_option('--title', action='store', type='string')
  parser.add_option('--uri', action='store', type='string')
  parser.add_option('--send_notification', action='store_const', dest='mode', const='send_notification')
  parser.add_option('--subscribe_user', action='store_const', dest='mode', const='subscribe_user', help='switches to subscribe mode')

  (options, args) = parser.parse_args()

  if options.mode == 'send_notification':
    message = sys.stdin.read().strip()

    for recip in args:
      print "Sending message to %s ..." % recip
      result = json.loads(send_notification(recip, message, options.title, options.uri))
      print "  %s %s: %s" % (result['status'], result['response_code'], result['response_message'])
  elif options.mode == 'subscribe_user':
    for recip in args:
      print "Subscribing user %s ..." % recip
      result = json.loads(subscribe_user(recip))
      print "  %s %s: %s" % (result['status'], result['response_code'], result['response_message'])
	
if __name__=='__main__':
  main()
