#!/bin/bash

# Start up an iPython session with the correct environment. We check to
# see if a snpy profile exists and if so, use it. Otherwise set one up
# first

SCRIPT_VERSION=1.0

HELP=$(cat << END
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:
END
)

STARTUP=$(cat << END2
from snpy import version
print(" version {}".format(version.__version__))

from numpy import *
from matplotlib.pyplot import *
from snpy import *
import os

if os.environ['SNPY_DATABASE'] in sqlmod.databases:
   sqlmod.setSQL(os.environ['SNPY_DATABASE'])


if os.environ['SNPY_NOCHECK'] == "False":
   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")
END2
)

database="default"
nocheck=False
os=$(uname -s)
if [ "$os" = "Darwin" ] ; then
   gui=osx
else
   gui=tk
fi


function show_help {
   echo -e "$HELP"
   echo -n "           "
   python -c "import snpy.sqlmod;print(','.join(snpy.sqlmod.databases.keys()))"
   }

while [[ $# -gt 0 ]] ; do
   key="$1"

   case $key in
      -h)
         show_help
         exit 0
         ;;
      -nc)
         nocheck="True"
         shift
         ;;
      -gui)
         gui=$1
         shift
         ;;
      *)
         database=$1
         shift
         ;;
   esac
done

# Now we check for snpy profile
loc=$(ipython locate profile snpy)
if [ $? -eq 1 ] ; then
   echo "Setting up a SNooPy profile for the first time..."
   ipython profile create snpy > /dev/null 2&>1
   loc=$(ipython profile locate snpy)
   echo "c.InteractiveShell.banner1 = ''" >> $loc/ipython_config.py
   echo "c.InteractiveShell.banner2 = 'Welcome to SNooPy'" >> $loc/ipython_config.py
   echo "$STARTUP" > $loc/startup/00snpy_${SCRIPT_VERSION}.py
   echo "Done! Saved in $loc"
fi

if [ ! -f ${loc}/startup/00snpy_${SCRIPT_VERSION}.py ] ; then
   # Can't find the version we want. We probably need to update
   echo "Updating profile to latest version..."
   rm -f ${loc}/startup/00snpy*
   echo "$STARTUP" > ${loc}/startup/00snpy_${SCRIPT_VERSION}.py
   echo "Done!"
fi

SNPY_NOCHECK=$nocheck SNPY_DATABASE=$database ipython --profile=snpy --pylab=${gui} -i
