#! /usr/bin/python
# -*- coding: utf-8 -*-
# 
# Find out who has the support for today, divert the phone to them and send them an SMS telling they have support
#
# Copyright (C) Varnish Software AS 2012
#
# Written by Tollef Fog Heen <tfheen@varnish-software.com>
#

import gdata.auth
import gdata.spreadsheet
import gdata.spreadsheet.service
import sys
import json
import ldap

import time
import datetime as _datetime
from datetime import datetime, date
import gammu
import ConfigParser

sm = gammu.StateMachine()
sm.ReadConfig()
sm.Init()

BASEDN = "ADD YOUR LDAP BASE DN HERE"
LDAPSERVER = "ldap.example.com"

DEBUG = False
TOKEN = 'GRAB THIS FROM GDOCS'
wksh_id = "od6" # usually right for the first worksheet
sp_id = "ID_OF_SPREADSHEET"
conf = "/var/local/support-phone-status.conf"

c = ConfigParser.SafeConfigParser()
c.read(conf)

lastsms = 0
try:
    lastsms = c.getint('DEFAULT', 'lastsms')
except ConfigParser.NoOptionError:
    pass

token = gdata.auth.AuthSubToken()
token.set_token_string(TOKEN)
gd_client = gdata.spreadsheet.service.SpreadsheetsService()
gd_client.debug = DEBUG
gd_client.SetAuthSubToken(token)
feed = gd_client.GetListFeed(sp_id, wksh_id)

today = date.today()

def get_one_ldap_field(ldapconn, user, field):
    f = "(uid=%s)" % (user, )
    results = ldapconn.search_s(BASEDN, ldap.SCOPE_SUBTREE, f)
    if len(results) != 1:
        raise Exception("Oops, didn't find the right user (%s), please help!" % (user, ))
    dn,entry = results[0]
    return entry[field][0]

for entry in feed.entry:
    edate = date(*time.strptime(entry.custom["date"].text, '%m/%d/%Y')[:3])
    if edate == today:
        user = entry.custom["supportperson"].text

        for key in entry.custom:
            print '  %s: %s' % (key, entry.custom[key].text) 

        ld = ldap.initialize('ldap://' + LDAPSERVER)
        ld.simple_bind_s()

        mobile = get_one_ldap_field(ld, user, "mobile")
        sm.SetCallDivert(Divert = 'AllTypes', Type = 'All',
                         Number = mobile,
                         Timeout=0)

        lastperson = None
        try:
            lastperson = c.get("DEFAULT", "lastperson")
            lastmobile = c.get("DEFAULT", "lastmobile")
            if lastperson != user:
                # Tell them they're off duty
                message = {
                    'Text': u'You are now off duty, - support@varnish',
                    'SMSC': {'Location': 1},
                    'Number': lastmobile
                    }
                sm.SendSMS(message)
        except ConfigParser.NoOptionError:
            # No previous person, skip
            pass

        if (time.time() - lastsms >= 86400) or lastperson != user:
            # More than 24 hours or new user  → send SMS
            message = {
                'Text': u'You have support today, - support@varnish',
                'SMSC': {'Location': 1},
                'Number': mobile
            }
            sm.SendSMS(message)

            dt = datetime.combine(date.today(), _datetime.time(hour=9, minute=0))
            t = int(time.mktime(dt.timetuple()))

            c.set('DEFAULT', 'lastsms', str(t))
            c.set('DEFAULT', 'lastperson', user)
            c.set('DEFAULT', 'lastmobile', mobile)
            c.set('DEFAULT', 'lastsms-readable', time.ctime())
            with open(conf, 'wb') as configfile:
                c.write(configfile)
        break
