#!/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

	FLAGS="-DENABLE_PACKAGING=ON -DDEB_DETECT_DEPENDENCIES=ON -DPYTHON_BINDINGS=ON -DWITH_EXAMPLES=ON"

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

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

	echo "### make"
	make
	if [ "$TRAVIS" = "true" ] ; then
		# make sure the *.so can be found during make package
		echo "### Installing package as root"
		sudo make install
		# get rid of anything that will cause a problem
		echo "### Deleting install_manifest.txt (created as root)"
		sudo rm ./install_manifest.txt
	fi
	if command_exists sphinx-build ; then
		# to build the python doc, libiio and py-iio need to be installed
		# so we need to re-do some minor things now that they are
		FLAGS="${FLAGS} -DWITH_DOC=ON -DWITH_MAN=ON"
		echo "### cmake ${FLAGS}"
		cmake ${FLAGS} ..
		echo "### make"
		make
		# check the error output if either file isn't 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"
			ls -l Dox_output_csharp Dox_output_libiio 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() {
	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}

