#!/bin/bash
#
# Generate a build area for a given binary tag.
#
# cmake_config binary_tag [ project_path ] [ -- CMAKE options...]
#
# If no project_path is given, it is assumed to '.'
#
# In this case a new directory with the name of the binary_tag is created
# as the build directory. Otherwise the project_path is taken as given
# and the current directory is assumed to be the build directory.
#

set -e

usage()
{
  echo "usage: $(basename $0)  [<binary_tag>] [ <project_path> ] [ -- CMAKE options...]"
  exit 1
}

if [ $# -lt 0 ]; then
    usage
fi

if [ -z "${1}" -o  "${1}" == "--" ]
then
  if [ -z "${BINARY_TAG}" ]
  then
    echo "var is unset";
    # no binary tag
    UNAME=`uname -r`
    case "${UNAME}" in
      *)
          export BINARY_TAG="x86_64-el9-gcc15-opt"
          ;;
    esac
  fi
else
  export BINARY_TAG=${1}
  shift
fi

case ${BINARY_TAG} in
    *-icc180-opt)
        args="-DCMAKE_BUILD_TYPE=Release -DBoost_COMPILER=-gcc11"
	;;
    *-icc180-dbg)
        args="-DCMAKE_BUILD_TYPE=Debug -DBoost_COMPILER=-gcc11"
	;;
    *-opt)
        args=-DCMAKE_BUILD_TYPE=Release
        ;;
    *-dbg)
        args=-DCMAKE_BUILD_TYPE=Debug
        ;;
    *)
        echo "Invalid binary tag: ${BINARY_TAG}"
        exit 1
        ;;
esac


if [ -z "${1}" -o  "${1}" == "--" ]
then
    # no project path
    mkdir -p ${BINARY_TAG} || exit 1
    project=$(readlink -f .)
    cd ${BINARY_TAG} || exit 1
elif [ ! -z "${1}" -a "${1}" != "--" ]
then
    project=${1}
    shift
    if [ -f CMakeLists.txt ]; then
      echo "You have a CMakeLists.txt file in what is supposed to be your build directory - exiting"
      exit 1
    fi
fi

if [ "${1}" == "--" ]
then
    shift
fi

cmake -DBUILDNAME=${BINARY_TAG} -DBINARY_TAG=${BINARY_TAG} -DCMAKE_MODULE_PATH=$(readlink -f $(dirname $(dirname $0)))/cmake/modules ${args}  "$@" ${project}
unset args project
