#!/bin/sh -e

if [ "x${COVERITY_SCAN_PROJECT_NAME}" != "x" ] ; then exit 0; fi

. CI/travis/lib.sh

handle_default() {
	echo "### making build dir"
	mkdir -p build
	cd build

	add_python_path
	if command_exists python ; then
		command -v python
		python --version

		PYTHON_HELP="-DPYTHON_BINDINGS=ON \
			-DPYTHON_INCLUDE_DIR=$(python -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())") \
			-DPYTHON_LIBRARY=$(python -c "import distutils.sysconfig as sysconfig; print(sysconfig.get_config_var('LIBDIR'))") \
			-DPYTHON_EXECUTABLE=$(command -v python)"
		if command_exists sphinx-build ; then
			DOC_HELP="-DWITH_DOC=ON"
		fi
	else
		echo No Python
		if command_exists doxygen ; then
			DOC_HELP="-DWITH_DOC=ON"
		fi
	fi
	if [ ! -n "${DOC_HELP}" ] ; then
		if command_exists man2html ; then
			echo doc and man
			MAN_HELP="-DWITH_MAN=ON"
		fi
	else
		MAN_HELP="-DWITH_MAN=ON"
	fi

	FLAGS="-DENABLE_PACKAGING=ON -DDEB_DETECT_DEPENDENCIES=ON -DWITH_EXAMPLES=ON ${PYTHON_HELP} ${DOC_HELP} ${MAN_HELP}"

	echo "### cmake ${FLAGS}"
	cmake ${FLAGS} ..

	if [ -f CMakeFiles/CMakeError.log ] ; then
		echo "### CMakeError.log"
		cat CMakeFiles/CMakeError.log
	fi

	echo "### make"
	make

	# check the error output if either file is not empty
	if [ -s ./Dox_output_libiio -o -s ./Dox_output_csharp -o -s ./Spx_output_python ] ; then
		if [ -s ./Dox_output_libiio ] ; then
			echo "### ERRORs in Dox_output_libiio"
			cat ./Dox_output_libiio
		fi
		if [ -s ./Dox_output_csharp ] ; then
			echo "### ERRORs in Dox_output_csharp"
			cat ./Dox_output_csharp
		fi
		if [ -s ./Spx_output_python ] ; then
			echo "### ERRRORs in Spx_output_python"
			cat ./Spx_output_python
		fi
		exit 1
	else
		echo "### No errors in Doc"
		if [ -f Dox_output_csharp ] ; then
			ls -l Dox_output_csharp
		fi
		if [ -f Dox_output_libiio ] ; then
			ls -l Dox_output_libiio
		fi
		if [ -f Spx_output_python ] ; then
			ls -l Spx_output_python
		fi
	fi

	echo "### make package"
	make package
	if [ -n "${GH_DOC_TOKEN}" ] && \
			[ -f "./generateDocumentationAndDeploy.sh" ] ; then
		sh generateDocumentationAndDeploy.sh
	fi
	cd ..

	# make sure we are up to date (once)
	if [ "$LDIST" = "DO_NOT_DEPLOY" ] ; then
		./CI/travis/check_kernel.sh
	fi
	echo "### All done building"
}

handle_centos() {
	echo "handle centos"
	mkdir -p build
	cd build
	cmake -DENABLE_PACKAGING=ON -DPYTHON_BINDINGS=ON ..
	make
	make package
	cd ..
}

handle_centos_docker() {
	run_docker_script inside_docker.sh \
		"centos:centos${OS_VERSION}" "centos"
}

handle_ubuntu_docker() {
	run_docker_script inside_docker.sh \
		"ubuntu:${OS_VERSION}"
}

LIBNAME="$1"
OS_TYPE=${2:-default}

handle_${OS_TYPE}

