#!/bin/sh

set -ex

# Setup parallel compilation if MAKEFLAGS not already set
cd "$(dirname "$0")"
if [ -z "${MAKEFLAGS}" ]; then
  makeflags_value=$(Rscript scripts/setup-makeflags.R 2>/dev/null || echo "")
  if [ -n "${makeflags_value}" ]; then
    export MAKEFLAGS="${makeflags_value}"
    echo "Setting MAKEFLAGS=${makeflags_value} for parallel compilation"
    echo "Set NOT_CRAN or MAKEFLAGS to override"
  fi
else
  echo "MAKEFLAGS already set to: ${MAKEFLAGS}"
fi

cd "$(dirname "$0")/src"

# Not used on Linux, for completeness.
echo DUCKDB_RSTRTMGR=1 > Makevars.rstrtmgr
echo DUCKDB_RSTRTMGR_LIB= >> Makevars.rstrtmgr


# The purpose of this is to avoid rebuilding duckdb in every CI/CD run.
# We set the DUCKDB_R_PREBUILT_ARCHIVE environment variable to a file path
# that contains a .tar of all object files.
# This .tar file is cached and restored in CI/CD, keyed by compiler, OS,
# and hash of the duckdb/src subtree.
#
# Depending on the availability of the file, we either use the object files
# (via the rules in include/from-tar.mk), or create them as usual
# (via include/to-tar.mk). In the latter case, if the DUCKDB_R_PREBUILT_ARCHIVE
# environment variable is set, the .tar file is created.
#
# For local installations, this is typically not needed
# because ccache achieves the same purpose but better.
# In CI/CD, this approach gives better results than ccache.
#
# This logic is identical for Windows or non-Windows builds,
# only that we need to-tar-win.mk instead of to-tar.mk on Windows.

if [ -f "${DUCKDB_R_PREBUILT_ARCHIVE}" ] && tar -xm -f "${DUCKDB_R_PREBUILT_ARCHIVE}"; then
  cp include/from-tar.mk Makevars.duckdb
else
  cp include/to-tar.mk Makevars.duckdb
fi

# The duckdb sources are xz-compressed in the tarball to keep it under 5000000 bytes.
# This happens in the cleanup script.

if [ -f duckdb.tar.xz ]; then
  tar xJf duckdb.tar.xz
fi
