#!/bin/sh -e

TOP_DIR=$(pwd)

set -x

install_deps() {
	echo "# INSTALLING DEPENDENCIES"

	sudo apt-get -qq update
	echo "libm2k packages"
	sudo DEBIAN_FRONTEND=noninteractive apt-get install -y cmake doxygen graphviz \
		libaio-dev libavahi-client-dev libavahi-common-dev libusb-1.0-0-dev \
		libxml2-dev rpm tar bzip2 gzip flex bison git curl \
		python3-dev python3-setuptools python3-pip python3-all \
		debhelper devscripts fakeroot libserialport-dev swig dh-python \
		libunwind-dev libunwind8

	# libiio dependencies
	echo "libiio packages"
    sudo DEBIAN_FRONTEND=noninteractive apt-get install -y \
        libxml2-dev bison flex libcdk5-dev cmake \
        libaio-dev libusb-1.0-0-dev \
        libserialport-dev libavahi-client-dev man2html \
		python3-sphinx
}

install_glog() {
	echo "## Building glog"

	cd ${TOP_DIR}
	git clone --branch v0.4.0 --depth 1 https://github.com/google/glog
	mkdir -p glog/build_0_4_0 && cd glog/build_0_4_0
	cmake -DCMAKE_PREFIX_PATH=/usr ..
	make
	sudo make install
	sudo pip3 install --upgrade pip stdeb argparse
}

install_libiio() {
	echo "## Building libiio - version $LIBIIO_VERSION"

	cd ${TOP_DIR}
	git clone https://github.com/analogdevicesinc/libiio.git -b $LIBIIO_VERSION libiio
	mkdir ./libiio/build && cd ./libiio/build
    cmake .. -Werror=dev -DCOMPILE_WARNING_AS_ERROR=ON -DENABLE_PACKAGING=ON -DPYTHON_BINDINGS=ON -DWITH_DOC=ON -DWITH_SERIAL_BACKEND=ON -DWITH_MAN=ON -DCPACK_SYSTEM_NAME=${ARTIFACTNAME}
	make
	make package 
	sudo apt install ./libiio-*.deb
}

handle_default() {
	install_deps
	install_glog
	install_libiio
}

handle_ubuntu_docker() {
	handle_default
}

handle_doxygen() {
	# Install a recent version of doxygen
	DOXYGEN_URL="wget https://sourceforge.net/projects/doxygen/files/rel-1.8.15/doxygen-1.8.15.src.tar.gz"
	cd ${DEPS_DIR}
	[ -d "doxygen" ] || {
		mkdir doxygen && wget --quiet -O - ${DOXYGEN_URL} | tar --strip-components=1 -xz -C doxygen
	}
	cd doxygen
	mkdir -p build && cd build
	cmake ..
	make -j${NUM_JOBS}
	sudo make install
	cd ..
	cd ..

	cd ${TOP_DIR}/doc
	mkdir -p build && cd build
	cmake ..
	cd ..
	cd ..

	handle_default
	cd ${TOP_DIR}
	#Also install Sphinx for Python bindings
	sudo apt-get install python3-sphinx
	sudo pip3 install --upgrade sphinx_rtd_theme
}

handle_${OS_TYPE}
