#!/bin/sh
_skip_for_python='''' 
eval 'exec python${0##*ipbori} $0 "$@" '
'''
del _skip_for_python
#!python
# 
# @author Alexander Dreyer
# @date 2007-10-19
# Copyright: (c) 2007-2011 by The PolyBoRi Team
"""ipbori -- An interactive shell for PolyBoRi 0.8.3

This starts an interactive python-based shell -- IPython where available --
which imports the PolyBoRi framework.

"""
from optparse import OptionParser
parser = OptionParser()

parser.add_option("-t", "--test", 
                  action="store_true", dest="test", default=False,
                  help="Run doctests")

parser.add_option("-v", "--verbose", 
                  action="store_true", dest="verbose", default=False,
                  help="Be eloquent")

(opts, args) = parser.parse_args()

import os, sys

polybori_site = "../../../lib/python2.7/site-packages"
polybori_version = "0.8.3"

# Note: $PBORI_SITE is replaced on installation with relative path 
# to the PolyBoRi python site
if polybori_site.startswith('$'):
  polybori_site = os.path.join(os.pardir, "pyroot")

if polybori_version.startswith('$'):
  polybori_version = \
      open(os.path.realpath(os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                         os.pardir,'versionnumber')), 
           'r').read().replace('-','.')

polybori_dir = \
    os.path.normpath(os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                  polybori_site))

sys.path.insert(0, polybori_dir)

def _test(args):
  print "Testing..."
  from glob import glob
  from imp import new_module
  from os.path import basename, dirname, splitext
  import doctest

  if args:
    files = args
  else:
    files = glob(os.path.join(polybori_dir, 'polybori/*.py'))

  failed = 0

  for file in files:
    try:
      module = new_module(file.replace('.','_'))
      content = open(file).read()
      from distutils.sysconfig import get_python_version
      if get_python_version() == '2.5':
          content = 'from __future__ import with_statement\n' + content

      exec content in module.__dict__ 

      # Some PolyBoRi modules do have optional (possibly hidden) dependencies
      if '_exists' in dir(module):
        if not module._exists():
          print "# Prerequisites for optional file", file, "missing. Skipping."
          continue


    except ImportError:
      print "# Error importing", file
      if opts.verbose:
        import traceback
        traceback.print_exc(file=sys.stdout)
      continue

    print sys.argv[0], '-t', file
    (failure_count, test_count) = doctest.testmod(module, verbose=opts.verbose)
    failed += failure_count
  
  if not failed: print 'OK'
  return failed


if opts.test:
  sys.exit(_test(args))


from polybori.frontend import *
polybori_start(globals())

def ipbori_shell(context):
  try:
    try:
      from IPython.frontend.terminal.interactiveshell import \
          TerminalInteractiveShell
      return TerminalInteractiveShell(user_ns = context,
                                      display_banner = True)
    except ImportError:
      import IPython.Shell
      return IPython.Shell.start(context)
      
  except:
    # Fallback to plain interactive python
    import code
    sys.ps1 = "In: "
    result = code.InteractiveConsole(context)
    result.mainloop = result.interact
    return result

# Call the available shell
ipbori_shell(globals()).mainloop()

