"""Helper routine to enable command line code to run in a
django project.



"""
import inspect, os, sys


_alreadyFoundProject = None
def findProject():
    """If called from within a Django project (project or
    app directory), it ensures the environment variable is set and
    the directory containin the apps is on the path.

    Returns the project directory.  If you get back None, something's screwy
    and you may not be inside a Django project.
    """
    global _alreadyFoundProject
    if _alreadyFoundProject:
        #print "already found..."
        return _alreadyFoundProject
    
    st = inspect.stack()
    #print "I am running in %s line %d" % (st[0][1], st[0][2])
    if len(st) > 1:
        caller = st[1]
        callerFileName = caller[1]
        #print "I was called from %s line %d" % (caller[1], caller[2])
        #print caller
    else:
        raise ValueError("this function must be called from another, not at top level")

    projDir = None
    callerDir = os.path.dirname(callerFileName)
    if os.path.isfile(os.path.join(callerDir, 'settings.py')):
        #we're running in the project dir
        projDir = callerDir
    else:
        parentDir = os.path.dirname(callerDir)
        if os.path.isfile(os.path.join(parentDir, 'settings.py')):
            #we're running in the app dir
            projDir = parentDir
    if projDir:
        if projDir not in sys.path:  #guard against multiple calls
            sys.path.insert(0, projDir)
        os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
        #print 'set project dir to', projDir
        _alreadyFoundProject = projDir

    return projDir
            
    
    

def callIt():
    x = prepareProject()


if __name__=='__main__':
    callIt()
    