THREADS=${1:-5}

# $1 - release/build
# $2 - cmake build-type
# $3 - $THREADS
# $4 - root directory
function build () {
	BUILD_DIR="$1"
	THREADS="$3"
	DIRECTORY=$(realpath "$4")

	echo "------------------------------------------------------------------------------" 1>&2
	echo "Building '$DIRECTORY' in $2 mode: Build dir is '$BUILD_DIR', threads: $THREADS" 1>&2
	echo "------------------------------------------------------------------------------" 1>&2

	./CMake/generate.py -wm || exit 1

	if [ ! -d "$BUILD_DIR" ] && [ ! -L "$BUILD_DIR" ]; then
		mkdir "$BUILD_DIR"
	fi

	if [ -L "${BUILD_DIR}" ]; then
		LINK=$(readlink "${BUILD_DIR}")
		if [ ! -d ${LINK} ]; then
			mkdir ${LINK}
		fi
		cd ${LINK}
		cmake -DCMAKE_BUILD_TYPE=$2 -DCMAKE_EXPORT_COMPILE_COMMANDS=ON ${DIRECTORY}
		cd ${DIRECTORY}/${BUILD_DIR}
	else
		cd "${BUILD_DIR}"
		cmake -DCMAKE_BUILD_TYPE=$2 -DCMAKE_EXPORT_COMPILE_COMMANDS=ON ..
	fi

	make -j${THREADS} || exit 1
	make test ARGS="-j${THREADS} --output-on-failure" || exit 1
}
