import SocketServer, hmac, cPickle, tempfile, os, shutil, time, subprocess, sys

class WakeupHandler(SocketServer.BaseRequestHandler):
    """
    A thread which runs on the actual voip server
    """
    def handle(self):
        obj = cPickle.load(self.request.makefile())
        self.request.close()
        m = hmac.new("2600")
        for s in ['phone', 'day', 'hh', 'mm', 'm', 'music', 'ip', 'user']:
            m.update(str(obj[s]))
        if m.digest() == obj['digest']:
            f, name = tempfile.mkstemp()
            f = os.fdopen(f, "w")
#CallerID: 6172537788
            f.write(
#"""Channel: Local/%s@trunkdirect
#MaxRetries: 2
#RetryTime: 30
#WaitTime: 10
#Application: Playback
#Data: %s
"""#
Channel: Local/%s@trunkdirect

MaxRetries: 3
RetryTime: 60
WaitTime: 30

Application: Playback
Data: %s

Callerid: Wakeup Call Service <999>
""" % (obj['phone'], obj['music'])
            )
            f.close()
            datestr = "%s %s:%s %s" % tuple(obj[s] for s in ['day', 'hh', 'mm', 'm'])
            os.chmod(name, 0666)
            os.system("date")
            print "%s [%s] to call %s at %s" % (obj['user'], obj['ip'], obj['phone'], datestr)
            sys.stdout.flush()
            #date = int(subprocess.Popen(['date', '-d', 
            #    "%s %s:%s %s" % tuple(obj[s] for s in ['day', 'hh', 'mm', 'm']),
            #    '+%s'],
            #    stdout=subprocess.PIPE).communicate()[0])
            #date = time.time() + int(obj['time'])
            #os.utime(name, (date, date))
            os.system("cat %s | sudo placecall '%s'" % (name, datestr))
print "wakeup server listening on 2667..."
SocketServer.TCPServer(('', 2667), WakeupHandler).serve_forever()
