#!/bin/bash
## Emacs please make this -*- mode: shell-mode; -*-
##
##  configure -- Unix build preparation system
##
##  Copyright (C) 2015  Dirk Eddelbuettel and Jeroen Ooms.
##
##  This file is part of Rblpapi
##
##  Rblpapi is free software: you can redistribute it and/or modify
##  it under the terms of the GNU General Public License as published by
##  the Free Software Foundation, either version 2 of the License, or
##  (at your option) any later version.
##
##  Rblpapi is distributed in the hope that it will be useful,
##  but WITHOUT ANY WARRANTY; without even the implied warranty of
##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##  GNU General Public License for more details.
##
##  You should have received a copy of the GNU General Public License
##  along with Rblpapi.  If not, see <http://www.gnu.org/licenses/>.

## Check that we are on Unix
uname=$(type -P uname)
if [ "${uname}" = "" ]; then
    echo "You do not have uname so this is unlikely to be a Unix system. Exiting."
    exit -1
fi

## Check for Linux or OSX
: ${R_HOME=$(R RHOME)}
sysname=$(${R_HOME}/bin/Rscript -e 'cat(Sys.info()["sysname"])')
if [ ${sysname} == "Linux" ]; then
    platform="linux"
    download="wget -q"
elif [ ${sysname} == "Darwin" ]; then
    platform="osx"
    download="curl -s -k -L -O"
else
    echo "Unsupported platform: $sysname"
    echo "Check http://www.bloomberglabs.com/api/libraries/ for possible support first."
    echo "Contributions welcome, see https://github.com/Rblp/blp for integration with Rblapi."
    exit -1
fi

## Populate Makevars
rpath=$(${R_HOME}/bin/Rscript -e 'cat(file.path(.libPaths()[1], "Rblpapi", "blp"))')
arch=$(uname -m)
if [ "${arch}" = "x86_64" ]; then
    echo "Setting up compilation for 64-bit system on ${platform}"
    sed -e"s/@config@/blpapi3_64/" -e"s|@rpath@|"${rpath}"|" src/Makevars.in > src/Makevars
    flavour="64"
elif [ "${arch}" = "i686" ]; then
    echo "Setting up compilation for 32-bit system on ${platform}"
    sed -e"s/@config@/blpapi3_32/" -e"s|@rpath@|"${rpath}"|" src/Makevars.in > src/Makevars
    flavour="32"
else
    echo "Unknown architecture: ${arch}. Exiting."
    exit -1
fi

## Get and install header files
(cd inst; 
    ${download} https://github.com/Rblp/blp/raw/master/headers/${platform}/blpHeaders.tar.gz; 
    tar xfz blpHeaders.tar.gz;
    rm blpHeaders.tar.gz)

## Get and install precompiled shared library
(cd inst;
    mkdir -p blp;
    cd blp;
    ${download} https://github.com/Rblp/blp/raw/master/${platform}${flavour}/blpLibrary.tar.gz
    tar xfz blpLibrary.tar.gz libblpapi3_${flavour}.so
    rm blpLibrary.tar.gz)

exit 0
