
##############################################################################
#
# Copyright (c) 2003-2017 by The University of Queensland
# http://www.uq.edu.au
#
# Primary Business: Queensland, Australia
# Licensed under the Apache License, version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
# Development until 2012 by Earth Systems Science Computational Center (ESSCC)
# Development 2012-2013 by School of Earth Sciences
# Development from 2014 by Centre for Geoscience Computing (GeoComp)
#
##############################################################################

import os
Import('*')

from subprocess import PIPE, Popen

haveMPL=False   # do we have matplotlib?
haveGD=False    # does matplotlib have griddata?

mplmagicversion='0.98.5'

# check for matplotlib
if env['pythoncmd']=='python':
  try:
    import matplotlib
    haveMPL=True
    mplversion=matplotlib.__version__
    from matplotlib.mlab import griddata
    haveGD=True
  except ImportError:
    pass
else:
  # we need to fire up the external command
    p=Popen([env['pythoncmd'], '-c', 'from __future__ import print_function;import matplotlib;print(matplotlib.__version__);from matplotlib.mlab import griddata;print("1")'], stdout=PIPE)
    try:
        mplversion=p.stdout.readline().strip()
        if mplversion!='':
           haveMPL=True
           hgd=p.stdout.readline().strip()
           haveGD=True
    except IOError:
        pass
    p.wait()

if not haveMPL:
    env['warnings'].append("matplotlib not found, will skip some unit tests")
else:
    if mplversion<mplmagicversion:
        env['warnings'].append("matplotlib found, but version too early. Some unit tests will be skipped.")

example_files_allow_mpi = []
example_files_no_mpi = []
example_deps = []
skipped_tests = []

def sortOutExample(name, needsGMSH=False, needsMPL=False, needsMagicMPL=False, needsGD=False, allowsMPI=True):
    if needsMagicMPL: needsMPL=True
    if needsGD: needsMPL=True
    if needsGMSH: allowsMPI=False

    if needsGMSH and not env['gmsh']:
        skipped_tests.append(name)
        return

    if (not needsGMSH or env['gmsh']) and (not needsMPL or haveMPL) and (not needsMagicMPL or mplversion>=mplmagicversion) and (not needsGD or haveGD):
        if allowsMPI:
            example_files_allow_mpi.append(name)
        else:
            example_files_no_mpi.append(name)
    else:
        example_deps.append(name)

# these are the release examples in example subdirectory:
#
#_deps is for files which end in .py and are required for
# testing but should not be invoked directly themselves

sortOutExample('usersguide/lid_driven_cavity.py')
sortOutExample('usersguide/mount.py')
sortOutExample('usersguide/heatedblock.py')
sortOutExample('usersguide/helmholtz.py')
sortOutExample('usersguide/fluid.py')
sortOutExample('usersguide/poisson.py')
sortOutExample('usersguide/diffusion.py')
sortOutExample('usersguide/poisson_vtk.py')
sortOutExample('usersguide/darcy.py')
sortOutExample('usersguide/dirac.py')
sortOutExample('usersguide/slip.py')
sortOutExample('usersguide/int_save.py')
sortOutExample('usersguide/wave.py', needsMPL=True)
sortOutExample('usersguide/trapezoid.py', needsGMSH=True, allowsMPI=False)
sortOutExample('usersguide/quad.py', needsGMSH=True)
sortOutExample('usersguide/brick.py', needsGMSH=True)
sortOutExample('usersguide/refine.py', needsGMSH=True)
sortOutExample('usersguide/poisson_matplotlib.py', needsGD=True, allowsMPI=False)
sortOutExample('usersguide/voxet_reader.py')

sortOutExample('geotutorial/steadystate_variablek.py')
sortOutExample('geotutorial/steadystate.py')
sortOutExample('geotutorial/forward_euler.py')
sortOutExample('geotutorial/myfirstscript.py')
sortOutExample('geotutorial/backward_euler.py')

example_deps.append('cookbook/cblib.py')
sortOutExample('cookbook/example01a.py')
sortOutExample('cookbook/example01b.py', needsMPL=True)
sortOutExample('cookbook/example01c.py', needsMPL=True, allowsMPI=False)
sortOutExample('cookbook/example02.py', needsMPL=True, allowsMPI=False)
sortOutExample('cookbook/example03a.py', needsGD=True, allowsMPI=False)
sortOutExample('cookbook/example03b.py')
sortOutExample('cookbook/example04a.py', needsGMSH=True)
sortOutExample('cookbook/example04b.py', needsGMSH=True, needsGD=True)
sortOutExample('cookbook/example05a.py', needsGMSH=True, needsGD=True)
sortOutExample('cookbook/example05b.py', needsGMSH=True, needsGD=True)
sortOutExample('cookbook/example05c.py', needsGMSH=True, needsGD=True, needsMagicMPL=True)
sortOutExample('cookbook/example06.py', needsGMSH=True, needsGD=True, needsMagicMPL=True)
sortOutExample('cookbook/example07a.py', needsMagicMPL=True, allowsMPI=False)
sortOutExample('cookbook/example07b.py', needsMagicMPL=True, allowsMPI=False)
sortOutExample('cookbook/example08a.py', needsMagicMPL=True, allowsMPI=False)
sortOutExample('cookbook/example08b.py', needsMagicMPL=True, allowsMPI=False)
sortOutExample('cookbook/example08c.py', needsMagicMPL=True, needsGMSH=True, allowsMPI=False)
sortOutExample('cookbook/example09m.py', needsMagicMPL=True, needsGMSH=True, allowsMPI=False)
sortOutExample('cookbook/example09a.py', needsMagicMPL=True, needsGMSH=True, allowsMPI=False)
#sortOutExample('cookbook/example09b.py', needsMagicMPL=True, needsGMSH=True, allowsMPI=False)
sortOutExample('cookbook/example10a.py', needsMagicMPL=True, allowsMPI=False)
sortOutExample('cookbook/example10b.py', needsMagicMPL=True, allowsMPI=False)
sortOutExample('cookbook/example10m.py', needsMagicMPL=True, needsGMSH=True, allowsMPI=False)
#sortOutExample('cookbook/example10c_0.py', needsMagicMPL=True, needsGMSH=True, allowsMPI=False)
#sortOutExample('cookbook/example10c_1.py', needsMagicMPL=True, needsGMSH=True, allowsMPI=False)
sortOutExample('cookbook/example11a.py', needsMagicMPL=True, allowsMPI=False)
sortOutExample('cookbook/example11b.py', needsMagicMPL=True, allowsMPI=False)

sortOutExample('inversion/create_netcdf.py')
sortOutExample('inversion/grav_ermapper.py')
sortOutExample('inversion/grav_netcdf.py')
sortOutExample('inversion/gravmag_netcdf.py')
sortOutExample('inversion/gravmag_nodriver.py')
sortOutExample('inversion/mag_netcdf.py')
sortOutExample('inversion/plot_ermapper.py', needsMPL=True, allowsMPI=False)
sortOutExample('inversion/plot_netcdf.py', needsMPL=True, allowsMPI=False)
sortOutExample('inversion/dc_forward.py', needsGMSH=True)


sortOutExample('inversion/test_commemi1.py', needsMPL=True, allowsMPI=True)
sortOutExample('inversion/test_commemi4.py', needsMPL=True, allowsMPI=True)

example_deps.append('inversion/content.txt')
example_deps.append('inversion/data/GravitySmall')
example_deps.append('inversion/data/MagneticSmall')
example_deps.append('inversion/data/QLDWestGravity')
example_deps.append('inversion/data/QLDWestMagnetic')
example_deps.append('inversion/data/GravitySmall.ers')
example_deps.append('inversion/data/MagneticSmall.ers')
example_deps.append('inversion/data/QLDWestGravity.ers')
example_deps.append('inversion/data/QLDWestMagnetic.ers')
example_deps.append('inversion/data/GravitySmall.nc')
example_deps.append('inversion/data/MagneticSmall.nc')
example_deps.append('inversion/data/QLDWestGravity.nc')
example_deps.append('inversion/data/QLDWestMagnetic.nc')
example_deps.append('inversion/data/HalfSphere_v1.4.msh')


if len(skipped_tests)>0:
    env['warnings'].append("gmsh not available. Skipping tests %s!"%' '.join(skipped_tests))

example_files = example_files_allow_mpi + example_files_no_mpi + example_deps

wave_examples = ['inversion/synthetic_HTI.py',
    'inversion/synthetic_VTI.py',
    'inversion/synthetic_TTI.py',
    'inversion/synthetic_sonic.py',
    'inversion/synthetic_sonicHTI.py']

for i in wave_examples:
    sortOutExample(i)

ex2=[os.path.join("examples", str(x)) for x in example_files]#+wave_examples]

#=============================================================================

local_env = env.Clone()
src_dir = local_env.Dir('.').srcnode().abspath
release_dir=os.path.join(env['prefix'],'release','doc')
Export('release_dir')

dir_cmd = "cd "+src_dir+" && "

# Need to use explicit tar/zip rather than the builder due to problems getting
# it not to put unwanted path components in the archive file
# --transform on tar is not supported on savanna
zip_path=os.path.join(release_dir, 'escript_examples.zip')
zip = local_env.Command(zip_path, None, dir_cmd+"zip "+zip_path+" "+" ".join(ex2))
env.Alias('examples_zipfile', zip)

tar_path=os.path.join(release_dir, 'escript_examples.tar')
targz_path=os.path.join(release_dir, 'escript_examples.tar.gz')
tar = local_env.Command(tar_path, None, dir_cmd+"tar -cf "+tar_path+" "+" ".join(ex2))
targz = local_env.Command(targz_path, tar, "gzip -n -9 "+tar_path)
env.Alias('examples_tarfile', targz)

#env=Environment(TARFLAGS = "-c -z",chdir=src_dir)
#if 'Tar' in dir(env):
# tar=env.Tar(tar_path, example_files, chdir=src_dir)
# env.Alias('examples_tarfile', tar)

local_env.SConscript(dirs = ['#/doc/cookbook'], variant_dir='cookbook', duplicate=1)
local_env.SConscript(dirs = ['#/doc/user'], variant_dir='user', duplicate=1)
local_env.SConscript(dirs = ['#/doc/inversion'], variant_dir='inversion', duplicate=1)
local_env.SConscript(dirs = ['#/doc/epydoc'], variant_dir='epydoc', duplicate=1)
local_env.SConscript(dirs = ['#/doc/sphinx_api'], variant_dir='sphinx_api', duplicate=1)
local_env.SConscript(dirs = ['#/doc/doxygen'], variant_dir='doxygen', duplicate=1)
local_env.SConscript(dirs = ['#/doc/install'], variant_dir='install', duplicate=1)
local_env.SConscript(dirs = ['#/doc/examples'], variant_dir='examples', duplicate=1, exports=['example_files_allow_mpi', 'example_files_no_mpi', 'example_deps'])

