#!/usr/bin/env python

import os,sys,re
import subprocess

fallback = '''
Sorry, this SNooPy does not seem to be installed in a virtualenv, so I don't
know where anything is.  You'll have to update SNooPy yourself:'''

fallback2 = '''
Sorry, I can't find the SNooPy source.  I  expected to find it here:
%s'''

instructions = '''
If you downloaded SNooPy with git:
1) Go to the SNooPy *source* folder and type 'git pull '
2) Type 'python setup.py install'
   NOTE:  make sure you use the correct python to do this.

If you downloaded a static source tarball:
1) Get the latest source from
   http://users.obs.carnegiescience.edu/cburns/downloads
2) Unpack the source , change directory to the snpy folder
   and type 'python setup.py install'
   NOTE:  make sure you use the correct python to do this.
'''

# first check to see if we are in a virtualenv
realprefix = getattr(sys, 'real_prefix', None)
baseprefix = getattr(sys, 'base_prefix', None)
has_conda = sys.version.lower().find('anaconda') >= 0 or\
            sys.version.lower().find('continuum analytics') > 0 

if realprefix is None and baseprefix is None and not has_conda:
   print(fallback)
   print(instructions)
   sys.exit(1)


# The prefix is the virtualenv on
snpy_src = os.path.join(sys.prefix, 'snpy')
if not os.path.isdir(snpy_src):
   print(fallback2 % snpy_src)
   print(instructions)
   sys.exit(1)

os.chdir(snpy_src)
if os.path.isdir('.git'):
   print("Trying to update from GIT repository...")
   p = subprocess.Popen(['git','pull'],
         stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
   p.wait()
   if p.returncode != 0:
      print("GIT pull command failed.  Here's what we got:")
      print(p.stdout.readlines())
      print(p.stderr.readlines())
      sys.exit(1)
   print("Success!")

   of = open('SNooPy.build.log','w')
   print("Building updated SNooPy source code...")
   #p = subprocess.Popen([os.path.join(sys.prefix, 'bin','python'),'setup.py',
   #   'install'], stdout=of, stderr=subprocess.STDOUT)
   p = subprocess.Popen([os.path.join(sys.prefix, 'bin','pip'),'install',
      '.'], stdout=of, stderr=subprocess.STDOUT)
   p.wait()
   if p.returncode != 0:
      print("Failed to build the updated SNooPy source code!")
      print("Check the output SNooPy.build.log file to see what went wrong")
      of.close()
      sys.exit(1)
   print("Success!  SNooPy is now up to date")


else:
   # find the correct pip command to update....
   print("Sorry, the SNooPy source does not appear to be a git working")
   print("copy.  You'll need to update by hand.")
   print(instructions)
   
