#!/bin/sh

## This allow for standard CRAN override preference for both a settable R_HOME
## with fallback to query R in $PATH for the value it has so it works both
## explicitly, implicitly from the running R instance or by pointing at alternate
## build when multiple R versions are installed (as CRAN does and some users do)
: ${R_HOME=`R RHOME`}
if test -z "${R_HOME}"; then
    echo Could not determine R_HOME.
    exit 1
fi

## Check for pkg-config and use it to inquire about tiledb and tiledbsoma build options
pkg-config --version >/dev/null 2>&1
if [ $? -eq 0 ]; then
    pkg-config --exists tiledb tiledbsoma
    if [ $? -eq 0 ]; then
        pkgcflags=`pkg-config --cflags tiledb tiledbsoma`
        pkglibs=`pkg-config --libs tiledb tiledbsoma`

        ## substitute them in (leaving @tiledb_rpath@ and @cxx20_macos@ alone for now)
        sed -e "s|@tiledb_include@|$pkgcflags |" \
            -e "s|@tiledb_libs@|$pkglibs|" \
            -e "s|@tiledb_rpath@||" \
            -e "s|@cxx20_macos@||" \
            src/Makevars.in > src/Makevars

        echo "** updated src/Makevars for system library via pkg-config"

        ## we can exit now as we have a working setup
        exit 0
    fi
fi

## If we are still here `pkg-config` alone did not work.

## Download tiledb pre-made
${R_HOME}/bin/Rscript tools/get_tarball.R

## Check for cmake and git
${R_HOME}/bin/Rscript tools/check_cmake_and_git.R

## Make libtiledbsoma library using cmake (and an added git dependency)
export CC="`${R_HOME}/bin/R CMD config CC`"
export CXX="`${R_HOME}/bin/R CMD config CXX`"
export CMAKE_OSX_ARCHITECTURES="`uname -m`"

## The 'build_libtiledbsoma.sh' script is made / finalised by an earlier script.
if [ ! -f tools/build_libtiledbsoma.sh ]; then
    exit 1
fi
tools/build_libtiledbsoma.sh

pkgincl="-I../inst/tiledb/include -I../inst/tiledbsoma/include -I../inst/tiledbsoma/include/tiledbsoma"
pkglibs="-ltiledb -L../inst/tiledb/lib -ltiledbsoma -L../inst/tiledbsoma/lib"
rpath="-Wl,-rpath,'\$\$ORIGIN/../tiledb/lib' -Wl,-rpath,'\$\$ORIGIN/../tiledbsoma/lib'"
macosver=`${R_HOME}/bin/Rscript -e 'if (Sys.info()["sysname"] == "Darwin") cat("-mmacosx-version-min=11.0") else cat("")'`

sed -e "s|@tiledb_include@|$pkgincl |" \
    -e "s|@tiledb_libs@|$pkglibs|" \
    -e "s|@tiledb_rpath@|$rpath|" \
    -e "s|@cxx20_macos@|$macosver|" \
    src/Makevars.in > src/Makevars
