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

	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 ${DIRECTORY}
		cd ${DIRECTORY}/${BUILD_DIR}
	else
		cd "${BUILD_DIR}"
		cmake -DCMAKE_BUILD_TYPE=$2 ..
	fi

	make -j${THREADS} || exit 1
	make test || exit 1

	# todo: everything below should be handled by cmake's make test and make install
	if [ ! -d bin ]; then
		mkdir bin
	fi

	rm bin/*
	cd bin
	find .. -executable -type f | grep -v 'CMakeFiles' | while read line; do ln -s $line $(basename $line); done

	cp ${DIRECTORY}/translateAddresses .
	cp ${DIRECTORY}/xmlFormat .

	cd ${DIRECTORY}

	for test in $(ls tests.*.sh); do \
		./${test} ${BUILD_DIR}/bin ${THREADS}; \
	done
}
