#!/usr/bin/env python
#--------------------------------#
# Author: V.garonne              #
# Mail: garonne@lal.in2p3.fr     #
# Description: script to build   #
# binaries and the tarball on a  #
# certain host                   #
#--------------------------------#

import os, sys, commands, string, glob
import shutil

def checkPythonVersion (major=1,minor=5):    
    version      = float(str(major) +'.'+ str(minor))
    if string.find(sys.version, '1.5') != -1:
        thisversion = float(1.5)
    else:
        thisversion  = float(str(sys.version_info[0]) + '.' + str(sys.version_info[1]))
    if    version > thisversion:
    # try to find the good python version >= 2.3
        paths = string.split(os.environ['PATH'],':')
        print 'hmmm look for the appropriate python version, this one is',\
        thisversion,'and the required version is python >=', version    
        pythons = []      
        for path in paths:
            pythons = glob.glob1(path, 'python*')
            for python in pythons:
                cmd = python +' -c "import sys; print sys.version"'
                status, thisversion = commands.getstatusoutput(cmd)
                if string.find(thisversion, '1.5') != -1:
                    thisversion = float(1.5)
                else:
                    cmd = python +' -c "import sys; print sys.version_info"'
                    status, thisversion = commands.getstatusoutput(cmd)
                    thisversion         = eval (str(thisversion))
                    thisversion         = float(str(thisversion[0]) +'.'+ str(thisversion[1]))
                if (thisversion >= version):
                    print 'found and load', python
                    sys.argv.insert (0, python)
                    os.execvp       (python, sys.argv)  
        print 'The appropriate version of python >=' + str(version) + ' is not here, check your PATH variable or install it'
        sys.exit(-1)
checkPythonVersion (2,2)

# for package version dependant
import tarfile
import urllib

# My own python 'tar -xvzf' in waiting python 2.5...
def extractall(tarball, path="."):
    tar         = tarfile.open(tarball)
    directories = []
    for tarinfo in tar:
        if tarinfo.isdir():
                try:
                    os.makedirs(os.path.join(path, tarinfo.name), 0777)
                except EnvironmentError:
                    pass
                directories.append(tarinfo)
        else:
            tar.extract(tarinfo, path)

    # Reverse sort directories.
    directories.sort   (lambda a, b: cmp(a.name, b.name))
    directories.reverse()

    # Set correct owner, mtime and filemode on directories.
    for tarinfo in directories:
        path = os.path.join(path, tarinfo.name)
        tar.chown(tarinfo, path)
        #tar.utime(tarinfo, path)
        #tar.chmod(tarinfo, path)
    tar.close()

        
#--------------------# MAIN #-------------------------#
if __name__ == '__main__':  
  
    # Check arguments
    checkPythonVersion(2,2)
    if len(sys.argv) != 3:
        print sys.arvg[0], '<version>' , '<platform>'
        sys.exit(-1)
    else:    
        version   = sys.argv[1]
        platform  = sys.argv[2]
        
    preambule = 'cmt_build_binaries >'
    tarball   = "CMT"+version+".tar.gz"
    www       = "http://www.cmtsite.org"
    here      = os.getcwd()
    
    # get or untar CMT source tarball
    if not os.path.exists(tarball):
        print preambule + 'the CMT tarball is not here'
        print preambule + 'try to get it from the web site '+ www 
        h = urllib.urlretrieve(www + '/' + version + '/' + tarball, tarball)
        if not os.path.exists(tarball):    
            print preambule + 'the CMT tarball is still not here'
            sys.exit(-1)
    
    # get real platform name
    if not (platform == 'VisualC' and sys.platform == 'cygwin'):        
        sysname  = os.uname() [0]
        machine  = os.uname() [4]
        platform = sysname + '-' + machine
        platform = string.replace (platform, ' ','')
    print preambule,'platform =', platform
   
    if os.path.exists('CMT'):
        try:
            shutil.rmtree('CMT')    
        except:
            pass
    print preambule + " untar "+tarball+" source tarball"
    extractall(tarball=tarball)
    
    
    # configure, compile and create bin tarball
    if platform == 'VisualC':
        f = open ('cmtnmake','w+')
        content = 'call rlogin.bat\n' 
        content = content + 'cd CMT\\'+version+'\mgr\n' 
        content = content + 'call INSTALL.bat\n'
        content = content + 'call setup.bat\n'
        content = content + 'nmake /f nmake\n'
        f.write (content)
        f.close()        
        cmd = 'cmd < cmtnmake'  
    else:
        os.chdir ("CMT/" + version + "/mgr")
        cmd= 'tcsh -c " ./INSTALL; source setup.csh ;'   
        if sys.platform == 'darwin':         
            cmd = cmd + 'make'
        elif sys.platform == 'cygwin':
            cmd = cmd + 'make'
        elif sys.platform == 'VisualC':
            cmd = cmd + 'setup.bat;'
            cmd = cmd + 'nmake /f nmake'
        else:
            cmd = cmd + 'gmake STATIC=1'
        cmd = cmd + '"'
    print  preambule + cmd 
    status, output = commands.getstatusoutput (cmd)
    print   output
    if platform == 'VisualC':
       os.remove('cmtnmake')
    
    print  preambule + ' first do the clean up for preparing archive'
    os.chdir(here)
    # first do the clean up
    files = ['cmt_deps', 'last-rebuild', 'CMT_setup.make', 'cmt_dependencies.make']
    for file in files:
        if os.path.exists      ('CMT/'+version+'/'+platform +'/' + file):
            if os.path.isdir   ('CMT/'+version+'/'+platform +'/' + file):
                shutil.rmtree  ('CMT/'+version+'/'+platform +'/' + file)
            else:
                os.remove      ('CMT/'+version+'/'+platform +'/' + file)

    if platform =='VisualC':
        shutil.rmtree ('CMT/'+version+'/'+platform+'/cmt' )
    else:
        if os.path.exists ('CMT/'+version+'/'+platform +'/cmt'):
            os.remove ('CMT/'+version+'/'+platform +'/cmt')
            os.chdir('CMT/'+version+'/'+platform +'/')
            os.symlink ('cmt.exe', 'cmt')
            os.chdir(here)
        files = glob.glob1('CMT/'+version+'/'+platform, '*.o')
        for file in files:
            print preambule + 'remove  CMT/'+version+'/'+platform + '/' +file
            os.remove ('CMT/'+version+'/'+platform + '/' +file)
                    
    print  preambule + ' do the tarball for ' + platform
    namelist = ['mgr', 'src', platform]
#    if platform == 'Linux-i686':
#            os.chdir('CMT/'+version)
#            os.symlink ('Linux-i686', 'Linux-x86_64') 
#            os.chdir(here)
#            namelist.append('Linux-x86_64') 
            
    tar      = tarfile.open("CMT"+version+platform+".tar.gz", "w:gz")
    for name in namelist:
        print preambule + ' add the file ' + name + ' to the bin archive'
        tar.add(name='CMT/'+version+'/'+ name, arcname='CMT'+'/'+version+'/'+name)
    tar.close()
#------------------------------- End of File --------------------------------------#