#!/bin/sh -e

set -ex

WORKDIR=$(pwd)

install_packages() {
    echo "### Installing packages"

    echo "#### Installing brew packages"
    BREW_LIBIIO="doxygen libusb libxml2 ncurses cdk libserialport sphinx-doc pkg-config"
    BREW_LIBM2K="cmake doxygen libusb libxml2 swig curl python"
    PACKAGES="$BREW_LIBIIO $BREW_LIBM2K"
    brew install --display-times $PACKAGES

    echo "#### Installing pip packages"
    PIP_LIBIIO="sphinx setuptools"
    PIP_LIBM2K="wheel twine build virtualenv"
    PACKAGES="$PIP_LIBIIO $PIP_LIBM2K"
    pip3 install $PACKAGES
}

build_glog() {
    echo "### Building glog - version $GLOG_VERSION"
    git clone https://github.com/google/glog -b $GLOG_VERSION "${WORKDIR}"/glog

    cd "${WORKDIR}"/glog
    mkdir -p build_"${GLOG_VERSION}" && cd build_"${GLOG_VERSION}"
    cmake "${WORKDIR}"/glog
    make
    sudo make install
    cd "${WORKDIR}"
}

build_libiio() {
    echo "### Building libiio - version $LIBIIO_VERSION"
    git clone https://github.com/analogdevicesinc/libiio.git -b $LIBIIO_VERSION "${WORKDIR}"/libiio

    echo "#### Building: .pkg"
    cd "${WORKDIR}"/libiio
    mkdir -p build && cd build
    cmake "${WORKDIR}"/libiio \
        -Werror=dev \
        -DCOMPILE_WARNING_AS_ERROR=ON \
        -DOSX_PACKAGE=ON \
        -DCPP_BINDINGS=ON \
        -DPYTHON_EXECUTABLE:FILEPATH=$(python -c "import os, sys; print(os.path.dirname(sys.executable) + '/python')") \
        -DPYTHON_BINDINGS=ON \
        -DWITH_EXAMPLES=ON \
        -DWITH_SERIAL_BACKEND=ON \
        -DWITH_ZSTD=OFF
    make
    sudo make install

    echo "#### Building: .tar"
    cd "${WORKDIR}"/libiio
    mkdir -p build_tar && cd build_tar
    cmake "${WORKDIR}"/libiio \
        -Werror=dev \
        -DCOMPILE_WARNING_AS_ERROR=ON \
        -DOSX_PACKAGE=OFF \
        -DENABLE_PACKAGING=ON \
        -DCPP_BINDINGS=ON \
        -DPYTHON_EXECUTABLE:FILEPATH=$(python -c "import os, sys; print(os.path.dirname(sys.executable) + '/python')") \
        -DPYTHON_BINDINGS=ON \
        -DWITH_SERIAL_BACKEND=ON \
        -DWITH_ZSTD=OFF \
        -DCPACK_SYSTEM_NAME=${ARTIFACTNAME}
    make package
    mv ../CI/azure/macos_tar_fixup.sh .
    chmod +x macos_tar_fixup.sh
    ./macos_tar_fixup.sh
    cd "${WORKDIR}"
    
    echo "#### Building with documentation"
    cd "${WORKDIR}"/libiio/build
    cmake "${WORKDIR}"/libiio \
        -Werror=dev \
        -DCOMPILE_WARNING_AS_ERROR=ON \
        -DCPP_BINDINGS=ON \
        -DPYTHON_BINDINGS=ON \
        -DWITH_DOC=ON \
        -DWITH_SERIAL_BACKEND=ON
    make
    cd "${WORKDIR}"
}

install_packages
build_glog
build_libiio