#! /bin/bash

set -eux

echo "Beginning project setup for SDRPlay interface." > build.log
date >> build.log
mkdir -p dependencies && pushd dependencies

# Install build dependencies
# Debian:
sudo apt-get update
sudo apt-get install -y \
    git build-essential automake cmake \
    libpulse-dev libgtk-3-dev \
    freeglut3 freeglut3-dev
# RedHat:
#sudo dnf install pulseaudio-libs-devel gtk3-devel freeglut-devel


# These are necessary for building the python bindings for SoapySDR.
# These must be installed before building SoapySDR for the python
# bindings to be available on the system.
sudo apt-get install -y python-dev swig


# Build SoapySDR
if ! [ -d SoapySDR ]; then
git clone https://github.com/pothosware/SoapySDR.git
pushd SoapySDR
    mkdir build
    pushd build
        cmake .. -DCMAKE_BUILD_TYPE=Release
        make -j
        sudo make install
        sudo ldconfig
        SoapySDRUtil --info #test SoapySDR install
    popd
popd
fi

# Build SoapySDRPlay plugin
if ! [ -d SoapySDRPlay ]; then
git clone https://github.com/pothosware/SoapySDRPlay.git
pushd SoapySDRPlay
    mkdir build
    pushd build
        cmake .. -DCMAKE_BUILD_TYPE=Release
        make
        sudo make install
        sudo ldconfig
        SoapySDRUtil --info
    popd
popd
fi

# SoapySDRPlay plugin can overwrite some of the installed files for SoapySDR with older
# versions - re-run the installer for SoapySDR base to ensure we have the latest ones.
pushd SoapySDR/build
    sudo make install
popd

# Build liquid-dsp
if ! [ -d liquid-dsp ]; then
git clone https://github.com/jgaeddert/liquid-dsp
pushd liquid-dsp
    ./bootstrap.sh
    CFLAGS="-march=native -O3" ./configure --enable-fftoverride
    make -j
    sudo make install
    sudo ldconfig
popd
fi

popd #dependencies
echo "Setup completed." >> build.log
date >> build.log
exit 0


########################### DONT NEED THIS STUFF ###################################
## Build wxWidgets
#if ! [ -d wxWidgets-3.2.1 ]; then
#wget https://github.com/wxWidgets/wxWidgets/releases/download/v3.2.1/wxWidgets-3.2.1.tar.bz2
#tar -xvjf wxWidgets-3.2.1.tar.bz2
#rm wxWidgets-3.2.1.tar.bz2
#pushd wxWidgets-3.2.1
#    ./autogen.sh
#    ./configure \
#        --with-opengl --disable-glcanvasegl --disable-shared --enable-monolithic \
#        --with-libjpeg --with-libtiff --with-libpng --with-zlib --disable-sdltest \
#        --enable-unicode --enable-display --enable-propgrid --disable-webview \
#        --disable-webviewwebkit CXXFLAGS="-std=c++0x"
#
#    make -j
#    sudo make install
#popd
#fi
#
## Build CubicSDR
#if ! [ -d CubicSDR ]; then
#git clone https://github.com/cjcliffe/CubicSDR.git
#pushd CubicSDR
#    mkdir build
#    pushd build
#        cmake ../ -DCMAKE_BUILD_TYPE=Release \
#            -DwxWidgets_CONFIG_EXECUTABLE=/usr/local/bin/wx-config
#        make -j
#        sudo make install
#    popd
#popd
#fi
