#!/usr/bin/env python
import sys,os,glob

if '-h' in sys.argv or '-help' in sys.argv:
   from snpy.sqlmod import databases
   print '''
SNooPy Startup Script.

Usage:  snpy [-gui gui] [-nc] [database]

        -gui gui:  select gui to use.  By default, 'tk' is
                   used on Linux and 'osx' on Macs.  You
                   can try 'tk' on Mac, but it tends to be 
                   less reliable
        -nc:  Don't check for newer versions at startup. Speeds up
              the startup time and good when no internet is available
        database:  Choose a database to query via SQL. Options listed below

Available Databases:
'''
   for key in databases:
      print "   %-10s:      %s" % (key,databases[key][1])
   sys.exit(0)

gui = 'tk'
if '-gui' in sys.argv:
   id = sys.argv.index('-gui')+1
   gui = sys.argv[id]
nc = '-nc' in sys.argv

if sys.platform.find('linux') >= 0:
   if getattr(sys, 'real_prefix', False):
      import Tkinter
      # Try out the tkinter
      try:
         root = Tkinter.Tk()
         root.withdraw()
      except:
         # Probably can't find init.tcl.  See if we can find it
         libdir = os.path.join(sys.real_prefix,'lib')
         tclver = Tkinter.tkinter.TCL_VERSION
         test_dirs = [os.path.join(libdir,'tcl'+tclver),
                      os.path.join(libdir,'tcl',tclver),
                      os.path.join(libdir,'tcl')]
         for dir in test_dirs:
            if os.path.isfile(os.path.join(dir,'init.tcl')):
               os.environ['TCL_LIBRARY'] = dir
               os.environ['TK_LIBRARY'] = dir.replace('tck','tk')
               break
         try:
            root = Tkinter.Tk()
            root.withdraw()
         except:
            print "Your python's Tkinter isn't installed or is broken.  Please"
            print "fix it.  You might try setting TCL_LIBRARY and TK_LIBRARY"
            print "appropriately."
            sys.exit(1)


from numpy import *

try:
   from IPython.terminal.embed import InteractiveShellEmbed
except:
   try:
      from IPython.frontend.terminal.embed import InteractiveShellEmbed
   except:
      print "You don't have an up-to-date version of ipython."
      print "SNooPy requires version 0.12 or greater"
      sys.exit(1)

ipshell=InteractiveShellEmbed(banner1='Welcome to SNooPy')
ipshell.enable_pylab(gui=gui)
from snpy import *

for key in sqlmod.databases:
   if key in sys.argv:
      sqlmod.setSQL(key)
      del sys.argv[sys.argv.index(key)]

# Check for newer version
if not nc:
   upgrade,message = check_version()
   if upgrade:
      print "**********************************"
      print "New version of SNooPy is Available"
      print "**********************************"
      for line in message:
         sys.stdout.write(line)
      print ""
      print "Use update-snpy to install this new version"
ipshell()
