import os

#teuchos_env = Environment()
Import('bas_env')

teuchos_env = bas_env.Clone()


def configureAndMake(target, source, env):
  # Whatever it takes to CONFIGURE and MAKE the TPL
  source_name = str(source[0])
  assert source_name == "packages/teuchos/configure.ac"

  target_name = str(target[0])

  (dir_name, target_filename) = os.path.split(target_name)
  assert dir_name == "packages/teuchos"
  #target_logfilename = os.path.splitext(target_filename)[0] + "Build.log"

  if not os.path.exists(target_name):
    print target_name, "does not exist! CONFIGURING, then MAKING..."

  ccflags = teuchos_env.Dictionary()['CCFLAGS']

  #extra_config_setting = "%s=%s" % (extra_flags_key, ccflags)
  # WJB: SCons and FFTW use CCFLAGS to specify debug vs. opt variant
  #      But for teuchos, it must be specified via CXXFLAGS, thus the
  #      flag_key/value substitution "trickery" in the next few lines

  cxx_flag_key = 'CXXFLAGS'
  extra_config_setting = "%s=%s" % (cxx_flag_key, ccflags)
  print "xtraConfigSetting = ", extra_config_setting

  cmd = 'cd ' + dir_name + ' && autoreconf -fi ' + ' > ' + target_filename
  cmd = cmd + ' ; ./configure ' + extra_config_setting
  cmd = cmd + ' --cache-file=config.cache --with-gnumake'
  cmd = cmd + ' --enable-teuchos'
  cmd = cmd + ' --disable-default-packages'
  cmd = cmd + ' >> ' + target_filename
  cmd = cmd + ' ; gmake -j2 >> ' + target_filename

  print "bldCmd = ", cmd
  os.system(cmd)

  return target_name


def buildTPL(target, source, env):
  target_name = configureAndMake(target, source, env)

  # WJB: prefer a target that is a derivative of the .a file -- unfortunately
  #      I have NOT had success in that area:  os.system("nm " + target_name + " > libteuchos_nm.txt")

  Touch("$TARGET")
  return 

teuchos_env.Command('#packages/teuchos/teuchosBuild.log',
                    '#packages/teuchos/configure.ac', buildTPL)


#dict = teuchos_env.Dictionary()
#keys = dict.keys()
#keys.sort()
#for key in keys:
#  print "construction variable = '%s', value = '%s'" % (key, dict[key])

