#!/usr/bin/env python

import os, sys

if len(sys.argv) != 2 or sys.argv[1][-4:]  != '.tar':
    print "Usage: %s sage-x.y.z.tar"%sys.argv[0]
    sys.exit(1)

tarball = sys.argv[1]
version = tarball[5:-4]

if not os.path.exists(tarball):
    print "%s: file %s does not exist"%(sys.argv[0], tarball)

r = tarball[:-4]
if os.path.exists(r):
    os.system('rm -rf %s'%r)

# extract sage-x.y.z.tar 
os.system('tar -xvf %s'%tarball)



############################################
## Make any modifications to sage_scripts ##
# Modify sage-make_relative, since we don't
# need to make Python scripts relative for
# the library install.
#
os.chdir('sage-%s'%version)
sage_scripts = 'sage_scripts-%s'%version
if os.system('tar -jxvf spkg/standard/%s.spkg'%sage_scripts):
    raise RuntimeError, "Error extract %s.spkg"%sage_scripts
F = open('%s/sage-make_relative'%sage_scripts,'w')
F.write('#!/usr/bin/env bash\n')
F.write('echo "Skipping making Python scripts relative."\n')
F.close()
if os.system('tar -jcvf spkg/standard/%s.spkg %s'%(sage_scripts, sage_scripts)):
    raise RuntimeError, "Error creating modified %s.spkg"%sage_scripts
os.system('rm -rf %s'%sage_scripts)
os.chdir('..')



############################################

# read list of needed packages

libdist_filelist = open('%s/spkg/standard/libdist_filelist'%r
                             ).read().split('\n')

bin = '%s/local/bin/'%r
os.makedirs(bin)

# delete existing makefile

os.unlink('%s/makefile'%r)

# deleted not necessary packages and
# touch appropriate installed files

os.makedirs('%s/spkg/installed'%r)

for F in os.listdir('%s/spkg/standard'%r):
    name, ext = os.path.splitext(F)
    i = name.find('-')
    name_without_version = name[:i]
    if len(ext) > 1 and not name_without_version in libdist_filelist:
        open('%s/spkg/installed/%s'%(r, name),'w').close()
        open('%s/spkg/standard/%s'%(r, F),'w').close()

# create setup.py file
setup = open('%s/setup.py'%r,'w')


# sorry, you're reading a python program that makes a python
# program that makes a shell script right now...

setup.write("""
import os, sys

#################################################
# Test that all pre-requisites are met in this Python install for
# using SAGE.
#################################################

SAGE_ROOT=os.path.abspath('.')
os.environ['PATH'] = os.environ['PATH'] + ':%s/local/bin/'%SAGE_ROOT

print "Checking prerequisites for installing the SAGE library..."

if sys.version_info[:2] < (2, 4):
    print "SAGE requires Python 2.4 or newer"
    sys.exit(1)
    
print "matplotlib..."
try:
    from matplotlib.backends.backend_agg import FigureCanvasAgg
    from matplotlib.transforms import Value
    from matplotlib.figure import Figure
    import matplotlib.patches as patches
    from matplotlib.cbook import flatten
except ImportError, msg:
    print msg
    print 'You must install matplotlib so that the above error does not occur.'
    sys.exit(1)

print "pyrex..."
try:
    import Pyrex
except ImportError, msg:
    print msg
    print 'You must install Pyrex first.'
    sys.exit(1)

print "pexpect..."
try:
    import pexpect
except ImportError, msg:
    print msg
    print 'You must install the Python pexpect library first.'
    sys.exit(1)

print "pyrexc..."
if os.system('which pyrexc 2>/dev/null 1>/dev/null'):
    print 'The pyrexec pyrex compiler must be in your PATH'
    sys.exit(1)

print "ZODB (Zope Object Database)..."
try:
    import ZODB
except ImportError, msg:
    print msg
    print 'You must install ZODB (the ZOPE Object Database).'
    sys.exit(1)

print "IPython..."    
try:
    import IPython
except ImportError, msg:
    print msg
    print 'You must install IPython first.'
    sys.exit(1)

print "gap..."
if os.system('which gap 2>/dev/null 1>/dev/null'):
    print 'WARNING: Much of SAGE will not work without GAP installed.'
    print 'Make sure the "gap" command is available.'
    sys.exit(1)

print "maxima..."
if os.system('which maxima 2>/dev/null 1>/dev/null'):
    print 'WARNING: Much of SAGE will not work without Maxima installed.'
    print 'Make sure the "maxima" command is available.'
    sys.exit(1)

print "flex..."
if os.system('which flex 2>/dev/null 1>/dev/null'):
    print 'The Singular component of SAGE requires flex to build. Please install.'
    print 'You must use the SAGE version of Singular (the standard version'
    print 'is missing important patches, etc.).'
    sys.exit(1)

print "bison..."
if os.system('which bison 2>/dev/null 1>/dev/null'):
    print 'The Singular component of SAGE requires bison to build. Please install.'
    print 'You must use the SAGE version of Singular (the standard version'
    print 'is missing important patches, etc.).'
    sys.exit(1)


#################################################
# Do the actual build and install
#################################################

python_exe = sys.executable
e = os.system('cd local/bin/; ln -sf %s python'%python_exe)
if e:
    raise RuntimeError, e
e = os.system('cd spkg; ./install all 2>&1 | tee -a ../install.log')
if e:
    raise RuntimeError, e

# create sage script
sage = open('sage','w')
sage.write(\"""
#!/usr/bin/env bash
# Change this if you move this directory.
SAGE_ROOT=%s
export SAGE_ROOT
LD_LIBRARY_PATH=$SAGE_ROOT/local/lib
export LD_LIBRARY_PATH

COMMAND="import sage.misc.interpreter; from sage.all import *; import os;"
ipython "$@" -p sage -c "$COMMAND"
\"""%os.path.abspath('.'))
sage.close()
os.system('chmod +x sage')

IP = '%s/.ipython/'%os.environ['HOME']
if not os.path.exists(IP):
    os.makedirs(IP)
os.system('cp ipythonrc-sage %s/'%IP)
""")
setup.close()

os.unlink('%s/sage'%r)


# mv ipythonrc to ipythonrc-sage

os.system('cp %s/ipythonrc %s/ipythonrc-sage'%(r,r))

ip = open('%s/ipythonrc'%r)
ipythonrc = ip.read()
ip.close()

ipythonrc_sage = open('%s/ipythonrc-sage'%r,'a')

ipythonrc_sage.write('\nexecute import sage.misc.interpreter\n')
ipythonrc_sage.write('\nexecute from sage.all import *; banner()\n')
ipythonrc_sage.write('\n#execute from pylab import *\n')
ipythonrc_sage.close()

os.unlink('%s/ipythonrc'%r)

# Ceate a README file.
    
readme = open('%s/README.txt'%r).read()

readme = """
This is the readme for sage-libdist, which is the
distribution of
   SAGE: Software for Algebra and Geometry Experimentation

INSTRUCTIONS:
   1. Make sure you have the following installed on your
      computer in a generic accessible location (these
      are the Debian package names):
            * python  (version 2.4)
            * python-dev  
            * libgmp3-dev
            
   2. As *root* (or via sudo), type
            python setup.py install
            
   3. Wait about 10 minutes.

   4. To run SAGE run the shell script "sage" in the
      current directory (you can copy this elsewhere).

   5. It is highly recommended that you obtain the following
      programs for your platform and install them:
              gap, singular, maxima
   
The following is the usual SAGE readme file.  It is for
the monolithic tarball install of SAGE.
""" + readme

open('%s/README.txt'%r,'w').write(readme)


i = r.find('-')
libdist = 'sage-libdist%s'%r[i:]

if os.path.exists(libdist):
    os.system('rm -rf %s'%libdist)

os.system('mv %s %s'%(r,libdist))

os.system('tar -cvf %s.tar %s'%(libdist,libdist))

os.system('rm -rf %s'%libdist)

