#! /usr/bin/python
##
# @file
# This file is part of SeisSol.
#
# @author Sebastian Rettenberger (sebastian.rettenberger AT tum.de, http://www5.in.tum.de/wiki/index.php/Sebastian_Rettenberger)
#
# @section LICENSE
# Copyright (c) 2015-2016, SeisSol Group
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 
# 1. Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
# 
# 3. Neither the name of the copyright holder nor the names of its
#    contributors may be used to endorse or promote products derived from this
#    software without specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

import os
import sys

#
# set possible variables
#
vars = Variables()

# read parameters from a file if given
vars.AddVariables(
  PathVariable( 'buildVariablesFile', 'location of the python file, which contains the build variables', None, PathVariable.PathIsFile )
)
env = Environment(variables=vars)
if 'buildVariablesFile' in env:
  vars = Variables(env['buildVariablesFile'])
  
# PUML specific variables
vars.AddVariables(
  PathVariable( 'buildDir', 'where to build the code', 'build', PathVariable.PathIsDirCreate ),
  
  EnumVariable( 'compileMode', 'mode of the compilation', 'release',
                allowed_values=('debug', 'release')
              ),

#  EnumVariable( 'parallelization', 'level of parallelization', 'none',
#                allowed_values=('none', 'mpi')
#              ),
  
#   BoolVariable( 'unitTests', 'builds additional unit tests',
#                 False
#               ),

  EnumVariable( 'logLevel',
                'logging level. \'debug\' prints all information available, \'info\' prints information at runtime (time step, plot number), \'warning\' prints warnings during runtime, \'error\' is most basic and prints errors only',
                'info',
                allowed_values=('debug', 'info', 'warning', 'error')
              )
)

env.Tool('PrefixPathTool')

# external variables
vars.AddVariables(
  env['PREFIX_PATH_VARIABLE'],
                  
  PathVariable( 'cc',
                'C compiler (default: gcc (serial), mpicc (parallel))',
                None,
                PathVariable.PathAccept ),
                  
  PathVariable( 'cxx',
                'C++ compiler (default: g++ (serial), mpiCC (parallel))',
                None,
                PathVariable.PathAccept ),
                
  BoolVariable( 'useExecutionEnvironment',
                'set variables set in the execution environment',
                True )
)

# generate help text
Help(vars.GenerateHelpText(env))
if '-h' in sys.argv or '--help' in sys.argv:
  import SCons
  print SCons.Script.help_text
  env.Exit()
  
# handle unknown, maybe misspelled variables
unknownVariables = vars.UnknownVariables()

# remove the buildVariablesFile from the list of unknown variables (used before)
if 'buildVariablesFile' in unknownVariables:
  unknownVariables.pop('buildVariablesFile')
  
# exit in the case of unknown variables
if unknownVariables:
  print "*** The following build variables are unknown: " + str(unknownVariables.keys())
  env.Exit(1)
  
# set environment
env = Environment(variables=vars)

# Not parallelization currently supported
env['parallelization'] = 'none'

# Set environment
if env['useExecutionEnvironment']:
  env['ENV'] = os.environ

#
# precompiler, compiler and linker flags
#

# set compiler
if 'cc' in env:
  env['CC'] = env['cxx']
else:
  if env['parallelization'] in ['mpi']:
    env['CC'] = 'mpicc'
  else:
    env['CC'] = 'gcc'

if 'cxx' in env:
  env['CXX'] = env['cxx']
else:
  if env['parallelization'] in ['mpi']:
    env['CXX'] = 'mpiCC'
  else:
    env['CXX'] = 'g++'

# add parallel flag for mpi
if env['parallelization'] in ['mpi']:
  env.Append(CPPDEFINES=['PARALLEL'])

# set level of logger
if env['logLevel'] == 'debug':
  env.Append(CPPDEFINES=['LOG_LEVEL=3'])
elif env['logLevel'] == 'info':
  env.Append(CPPDEFINES=['LOG_LEVEL=2'])
elif env['logLevel'] == 'warning':
  env.Append(CPPDEFINES=['LOG_LEVEL=1'])
elif env['logLevel'] == 'error':
  env.Append(CPPDEFINES=['LOG_LEVEL=0'])
else:
  assert(false)
  
# Use openmp
#env.Append(CXXFLAGS = ['-fopenmp'])
#env.Append(LINKFLAGS= ['-fopenmp'])

# compiler flags for generated kernels
env.Append(CXXFLAGS = ['-Wall', '-ansi', '-std=c++11'])
if env['compileMode'] == 'debug':
  env.Append(CXXFLAGS=['-O0','-g'])
elif env['compileMode'] == 'release':
  env.Append(CPPDEFINES=['NDEBUG'])
  env.Append(CXXFLAGS=['-O2'])

# add pathname to the list of directories which are search for include
env.Append(CPPPATH=['#/src'])
env.Append(CPPPATH=['#/submodules'])

# Add prefix path
env.Tool('PrefixPathTool')

#
# add libraries
#
# PStreams
env.Append(CPPPATH=['#/submodules/pstreams'])

# eigen3
env.Append(CPPPATH=['#/submodules/eigen3'])

# netCDF
env.Tool('NetcdfTool', parallel=(env['parallelization'] in ['mpi']), required=True)

# Proj4
env.Tool('ProjTool', required=True)

# PThread
env.Append(LIBS=['pthread'])

build_dir = 'build'

# build directory
env['execDir'] = env['buildDir']+'/bin'
env['buildDir'] = env['buildDir']+'/'+build_dir

# get the source files
env.sourceFiles = []

Export('env')
SConscript('src/SConscript', variant_dir='#/'+env['buildDir'], src_dir='#/', duplicate=0)
Import('env')

# build executable
env.Program('#/'+env['execDir']+'/asagiconv', env.sourceFiles)
