#!/bin/sh

home_dir=${PWD}

projectA_name="ProjA"
projectA_version="2.0.0"

# Create unique directory
tmploc=$(mktemp -dq -t temp.XXXXXX)

# Clean and exit
local_clean_exit() {
  cd ${home_dir}
  rm -rf ${tmploc}
  exit $1
}

echo "ELEMENTS_PROJECT_ROOT: ${ELEMENTS_PROJECT_ROOT}"

extra_proj_path=

if [ "$(basename ${ELEMENTS_PROJECT_ROOT})" = "Elements" ]; then
  par_dir=$(dirname ${ELEMENTS_PROJECT_ROOT})
  extra_proj_path=${par_dir}
else
  par_dir=$(dirname ${ELEMENTS_PROJECT_ROOT})
  if [  "$(basename ${par_dir})" = "Elements" ]; then
    extra_proj_path=$(dirname ${par_dir})
  fi
fi

echo "Internal CMAKE_PROJECT_PATH: ${extra_proj_path}"

if [ -z "${extra_proj_path}" ]; then
  echo "The internal CMAKE_POJECT_PATH is empty"
  local_clean_exit 0
fi

# Set to the User_area
export User_area=${tmploc}
export CMAKE_PROJECT_PATH=${tmploc}:${extra_proj_path}:${CMAKE_PROJECT_PATH}

echo "CMAKE_PROJECT_PATH: ${CMAKE_PROJECT_PATH}"
echo "BINARY_TAG: ${BINARY_TAG}"
echo "User_area ${User_area}"
echo "CMAKE_PREFIX_PATH: ${CMAKE_PREFIX_PATH}"



cd ${tmploc} || local_clean_exit 1

CreateElementsProject $projectA_name $projectA_version --yes

# Error? stop and clean up
if [ $? -ne 0 ]; then
   echo "Error: <CreateElementsProject $projectA_name $projectA_version> command failed!" 1>&2
   local_clean_exit 1
fi

# check that the Elements framework has been installed. It is
# not enough to have it built
if [ -e ${ELEMENTS_PROJECT_ROOT}/InstallArea/${BINARY_TAG}/manifest.xml ]; then

  cd $projectA_name/$projectA_version || local_clean_exit 1

  mkdir cmake
  cp ${ELEMENTS_PROJECT_ROOT}/InstallArea/${BINARY_TAG}/ElementsProjectConfig.cmake .

  make configure

  if [ $? -ne 0 ]; then
    echo "Error: <Configuration of $projectA_name $projectA_version> failed!" 1>&2
    local_clean_exit 1
  fi

  make

  if [ $? -ne 0 ]; then
    echo "Error: <Builld of $projectA_name $projectA_version> failed!" 1>&2
    local_clean_exit 1
  fi

  make install

  if [ $? -ne 0 ]; then
    echo "Error: <Installation of $projectA_name $projectA_version> failed!" 1>&2
    local_clean_exit 1
  fi

  if [ ! -e InstallArea/${BINARY_TAG}/manifest.xml ]; then
    echo "Error: <Installation of $projectA_name $projectA_version> failed!" 1>&2
    local_clean_exit 1
  fi




else
  echo "Warning: The Elements framework is not available in its InstallArea" 1>&2
fi


local_clean_exit 0
