#!/bin/bash -x

echo "Building for BUILD_TYPE = ${BUILD_TYPE}"
echo "Building with HOST_COMPILER = ${HOST_COMPILER}"
echo "Building in ${WORKSPACE}"

module use /home/projects/modulefiles

BUILD_TYPE=`echo $BUILD_TYPE | tr "~" " "`
build_options=""
for item in ${BUILD_TYPE}; do
  build_options="$build_options --with-$item"
done

kokkos_path=${WORKSPACE}/kokkos
gtest_path=${WORKSPACE}/kokkos/tpls/gtest

echo ${WORKSPACE}
pwd

#extract information from the provided parameters.
host_compiler_brand=`echo $HOST_COMPILER | grep -o "^[a-zA-Z]*"`
cuda_compiler=`echo $BUILD_TYPE | grep -o "cuda_[^ ]*"`

host_compiler_module=`echo $HOST_COMPILER | tr "_" "/"`
cuda_compiler_module=`echo $cuda_compiler | tr "_" "/"`
build_path=`echo $BUILD_TYPE | tr " " "_"`

module load $host_compiler_module
module load $cuda_compiler_module

case $host_compiler_brand in
  gcc)
    module load nvcc-wrapper/gnu
    compiler=g++
    ;;
  intel)
    module load nvcc-wrapper/intel
    compiler=icpc
    ;;
  *)
    echo "Unrecognized compiler brand."
    exit 1
    ;;
esac

#if cuda is on we need to set the host compiler for the
#nvcc wrapper and make the wrapper the compiler.
if [ $cuda_compiler != "" ]; then
  export NVCC_WRAPPER_DEFAULT_COMPILER=$compiler
  compiler=$kokkos_path/bin/nvcc_wrapper
fi

if [ $host_compiler_brand == "intel" -a $cuda_compiler != "" ]; then
  echo "Intel compilers are not supported with cuda at this time."
  exit 0
fi

rm -rf test-$build_path
mkdir test-$build_path
cd test-$build_path

/bin/bash $kokkos_path/generate_makefile.bash $build_options --kokkos-path="$kokkos_path" --with-gtest="$gtest_path" --compiler=$compiler 2>&1 |tee configure.out

if [ ${PIPESTATUS[0]} != 0 ]; then
  echo "Configure failed."
  exit 1
fi

make build-test 2>&1 | tee build.log

if [ ${PIPESTATUS[0]} != 0 ]; then
  echo "Build failed."
  exit 1
fi

make test 2>&1 | tee test.log

grep "FAIL" test.log
if [ $? == 0 ]; then
  echo "Tests failed."
  exit 1
fi
