#! /usr/bin/env python
#############################################################
#                                                           #
#   Author: Herve Menager                                   #
#   Organization:'Biological Software and Databases' Group, #
#                Institut Pasteur, Paris.                   #
#   Distributed under GPLv2 Licence. Please refer to the    #
#   COPYING.LIB document.                                   #
#                                                           #
#############################################################
import mb_cgi, re
from subprocess import Popen, PIPE

def process( self ):
    if( not(self.request.has_key('id') ) or not( self.request.has_key('db') )):
        self.jsonMap['errormsg'] = "Please specify a database and an identifier."
    else:
        db = self.request.getfirst('db').strip()
        id = self.request.getfirst('id').strip()
        params = {'db':db.encode('string_escape'), 'id':id.encode('string_escape')}
        path_exe , args = self.cfg.getDatabanksConfig()[db]['command']
        args =  args % params 
        args = args.split(' ')
        cmd= [ path_exe ]
        cmd.extend( args )
        checkParameterValue( 'db' , db )
        checkParameterValue( 'id' , id )
        # retrieving...
        process = Popen( cmd , shell = False , stdout = PIPE, stderr = PIPE )
        outText = ""
        for line in process.stdout :
            outText = outText + line

        errText = ""
        for line in process.stderr :
            errText = errText + line

        process.wait()
        returnCode = process.poll()
        
        if returnCode != 0 :
            outText = ""
        
        self.jsonMap['returnCode'] = str(returnCode)
        self.jsonMap['content'] = str(outText)
        self.jsonMap['errormsg'] = str(errText)
        

def checkParameterValue(name, value):
    """
    I{checkParameterValue} checks that a given parameter contains only alphanumeric characters
    This method is currently used only to log unusual entries, because the parameter values are escaped anyways to avoid injections.
    """
    ss = '^\w+$'
    m = re.match(ss,value)
    if(m==None):
        # TODO this should be properly logged in the Mobyle log system
        mb_cgi.c_log.warning("Unusual value in parameter " + name + "=" + value)

if __name__ == "__main__":
    mb_cgi.JSONCGI(processFunction=process)
