#!/usr/bin/env bash
##
## Copyright (C) HySoP 2011-2022
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
##         http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
##
set -feu -o pipefail

PYTHON_EXECUTABLE=${PYTHON_EXECUTABLE:-"$(which python3)"}
PYTHON_INCLUDE_DIR=$(${PYTHON_EXECUTABLE} -c "import sysconfig as sc; print(sc.get_paths()['include'])")
PYTHON_LIBRARY=$(${PYTHON_EXECUTABLE} -c "import sysconfig as sc, os; print(os.path.normpath(os.path.sep.join(sc.get_config_vars('LIBDIR', 'INSTSONAME'))))")

if [ $# -ne 5 ]; then
    echo "Usage ./config build_folder install_folder CC CXX FC"
    exit 1
fi

if [ -d "$1" ]; then
    echo "Folder $1 already exists."
    exit 1
fi

if [ -d "$2" ]; then
    echo "Folder $2 already exists."
    exit 1
fi

ROOT_DIR="$(pwd)"
BUILD_DIR="$1"
INSTALL_DIR="$2"

mkdir -p "${BUILD_DIR}"
cd "${BUILD_DIR}"

CC="$3" CXX="$4" FC="$5" cmake -DCMAKE_BUILD_TYPE=Release -DVERBOSE=OFF -DWITH_SCALES=ON -DHYSOP_INSTALL="${INSTALL_DIR}" -DFIND_FFTW_STATIC_ONLY=ON -DFIND_FFTW_VERBOSE=ON -DPython3_EXECUTABLE="${PYTHON_EXECUTABLE}" -DPython3_INCLUDE_DIR="${PYTHON_INCLUDE_DIR}" -DPython3_LIBRARY="${PYTHON_LIBRARY}" "${ROOT_DIR}"

if [ ! -f Makefile ]; then
    echo "The makefile has not been generated."
    exit 1
fi

exit 0
