#!/usr/bin/env python

import distutils.sysconfig as dist
import shutil
import os
import sys
import getopt

def usage():
    print """Usage:
    ./install [-p <prefix for asap binary>]
              [-m <where to install python module>]
              [-h] this message
    """

try:
    opts, args = getopt.getopt(sys.argv[1:], "p:m:h",
                               ["exec-prefix=", "module-dir=", "help"])

except getopt.GetoptError:
    usage()
    sys.exit(2)

execprefix = dist.EXEC_PREFIX
moduledir = dist.get_python_lib()
for k, v in opts:
    if k in ("-h", "--help"):
        usage()
        sys.exit()
    if k in ("-p", "--exec-prefix"):
        v = os.path.expanduser(v)
        v = os.path.expandvars(v)
        if not os.path.exists(v):
            print "The specified exec directory %s doesn't exist" % v
            sys.exit(1)
        p = os.path.join(v,"bin")
        if not os.path.exists(p):
            print "The specified exec directory %s doesn't exist" % p
            sys.exit(1)
        execprefix = v
    if k in ("-m", "--module-dir"):
        v = os.path.expanduser(v)
        v = os.path.expandvars(v)
        if not os.path.exists(v):
            print "The specified module directory %s doesn't exist" % v
            sys.exit(1)
        moduledir = v

print 'Looking for dependent modules...'
try:
    import matplotlib
except ImportError:
    print "Matplotlib not found"
    sys.exit(1)
if int(matplotlib.__version__.split(".")[1]) < 87:
    print "Warning: matplotlib version < 0.87." \
          "This might cause errors. Please upgrade."
try:
    import matplotlib.backends.backend_tkagg
except ImportError:
    print "Matplotlib doesn't have Tk support"
    sys.exit(1)
try:
    import numpy
except ImportError:
    try:
        import numarray
    except ImportError:
        print "You need to have either 'numpy' or 'numarray' installed."
        sys.exit(1)
try:
    import IPython
except ImportError:
    print "IPython should be installed."
    sys.exit(1)

print "All required modules were found."
moddir = os.path.join(moduledir, "asap")
bindir =  os.path.join(execprefix, "bin")
try:
    if os.path.exists(moddir):
        print "Found previous installation of ASAP. Removing..."
        shutil.rmtree(moddir)
    print "Installing asap module in %s" % moddir
    shutil.copytree("asap", moddir)
    print "Installing asap startup script in %s" % bindir
    shutil.copy2("bin/asap", bindir)
    shutil.copytree("data", os.path.join(moddir,"data"))
    print "Installation completed."
except OSError, oe:
    print oe
