#!/usr/bin/env python


import SimpleXMLRPCServer
import tempfile
import sys
import os
import time


debug = False

TMP_DIR  = '/var/spool/asterisk/tmp'

if os.sep == '\\':      # Windows
    SPOOL_DIR = '\\Altos02\var\spool\asterisk\outgoing'
    ARCH_DIR = '\\Altos02\var\spool\asterisk\outgoing_done'
else:
    SPOOL_DIR = '/var/spool/asterisk/outgoing'
    ARCH_DIR = '/var/spool/asterisk/outgoing_done'



def putcall(Channel, CallerId, MaxRetries, RetryTime, WaitTime, 
    Context, Extension, Priority, JobId, StartTime ):
    try:
        if Channel == '':
                raise Exception, 'Missing Channel'
        if Extension == '':
                raise Exception, 'Missing Extension'
      
        tempfile.tempdir = TMP_DIR
        destfn = tempfile.mktemp('.call')
        
        dfp = file(destfn, 'w+')
        dfp.write('Channel: %s\n' % Channel)
        dfp.write('CallerId: %s\n' % CallerId)
        dfp.write('MaxRetries: %d\n' % MaxRetries)
        dfp.write('RetryTime: %d\n' % RetryTime)
        dfp.write('WaitTime: %s\n' % WaitTime)
        dfp.write('Context: %s\n' % Context)
        dfp.write('Extension: %s\n' % Extension)
        dfp.write('Priority: %s\n' % Priority)
        dfp.write('Archive: yes\n')
        dfp.write('X-JobId: %s\n' % JobId)
        #dfp.write('X-StartTime: %s\n' % StartTime)
        dfp.close()
        
        newfn = os.path.join(SPOOL_DIR, '%.3f-%s.call' % (time.time(), JobId))

	modtime = time.mktime(time.strptime(str(StartTime), "%Y%m%dT%H:%M:%S"))
	if modtime > 0:
		acctime = time.time()
		os.utime(destfn, (acctime, modtime))
        
        os.rename(destfn, newfn)
        
        return (True,  'None', newfn)

    except Exception, v:
        return (False, str(v), 'None')


def getcallstatus(callfn):
    callfn = os.path.basename(callfn)
    if os.path.isfile(os.path.join(SPOOL_DIR,callfn)):
        return ('Queued', 'None')
    elif os.path.isfile(os.path.join(ARCH_DIR,callfn)):
    	Status = 'Unknown'
    	UniqueId = 'None'
        fh = file(os.path.join(ARCH_DIR,callfn))
        lines = fh.readlines()
        for line in lines:
            nv = line.strip().split(':')
            if len(nv) == 2:
                if nv[0].lower() == 'status':
                    Status = nv[1].strip()
                elif nv[0].lower() == 'uniquecallid':
                    UniqueId = nv[1].strip()
        return (Status, UniqueId)
    else:
        return ('NotFound', 'None')


def Service():
    server= SimpleXMLRPCServer.CGIXMLRPCRequestHandler()
    server.register_function(putcall)
    server.register_function(getcallstatus)
    server.handle_request()


if not debug:
    Service()
else:
    print getcallstatus('1129707459.852-1001.call')
