#!/www/python/bin/python -i
"""
$URL: svn+ssh://svn.mems-exchange.org/repos/trunk/dulcinea/bin/opendb $
$Id: opendb 28145 2006-04-04 17:51:31Z dbinger $

Opens a database and drops you into an interactive Python
interpreter with full access to the DB.
"""

import os
import sys
try:
    import readline, rlcompleter
    used = rlcompleter
    readline.parse_and_bind("tab: complete")
except ImportError:
    pass

from optparse import OptionParser

def main ():
    usage = "usage: %prog [options] [site]"
    parser = OptionParser(usage)
    parser.add_option('-q', '--quiet',
                      action='store_false', dest='verbose', default=1,
                      help="run quietly (no help message)")
    parser.add_option('-e', '--exec-file', dest='script_file',
                      metavar="FILE",
                      help="run FILE with execfile() after opening database")
    parser.add_option('-f', '--file',
                      help=("open FileStorage database in FILE "
                            "(conflicts with -d)"))
    (options, args) = parser.parse_args()

    if args:
        site = args[0]
    else:
        site = os.environ.get("SITE")
        if not site:
            parser.error("not enough arguments: must supply 'site' "
                         "if $SITE not set")
    os.environ["SITE"] = site

    from dulcinea.common import open_connection, get_connection
    from dulcinea.common import get_publisher
    from dulcinea.site_util import get_cache_size


    if options.file:
        connection = open_connection(filename=options.file) # file connection
    else:
        connection = get_connection() # open client connection

    connection.set_cache_size(get_cache_size(site))
    vardict = {}
    startup = os.environ.get("PYTHONSTARTUP")
    if startup and os.path.exists(startup):
        execfile(startup, vardict)
    print "\nLocals:  connection, root, commit(), abort(), publisher,"
    print ", ".join(sorted(connection.get_root().keys()))
    vardict.update(connection.get_root().items())
    print

    d = dict([('connection', connection),
              ('root', connection.get_root()),
              ('commit', connection.commit),
              ('abort', connection.abort),
              ('publisher', get_publisher())
              ])
    vardict.update(d)
    if options.script_file:
        print "executing %s..." % options.script_file
        execfile(options.script_file, vardict)

    try:
        from pyrepl.python_reader import ReaderConsole
        have_pyrepl = 1
    except ImportError:
        have_pyrepl = 0
    if have_pyrepl:
        from pyrepl.unix_console import UnixConsole
    try:
        con = UnixConsole(1, None)
    except AttributeError:
        # new version of UnixConsole has a different signature.
        con = UnixConsole()
        ReaderConsole(con, vardict).interact()
        sys.exit()

main()
