#!/bin/sh

echo "  checking runtime"

#architecture: x86_64,aarch64
#runtime: linux-gnu, windows, darwin20

runtime=`"${R_HOME}/bin/Rscript" -e 'cat(R.version$os)'`
architecture=`"${R_HOME}/bin/Rscript" -e 'cat(R.version$arch)'`

echo "  found: '$runtime'"
echo "   arch: '${architecture}'"

redatamurl=""

if [ "$runtime" = "linux-gnu" ]; then
  redatamurl="linux"
else
  #darwin20
  redatamurl="macos"
fi;

if [ "$architecture" != "x86_64" ]; then
  redatamurl="$redatamurl-arm64"
fi;


url="https://redatam-core.s3.us-west-2.amazonaws.com/core-dev/$redatamurl/redatamx-core-$redatamurl-20241010.zip"

echo "  using download from '$url'"

echo "  checking REDATAM libraries"

allok=yes

mkdir -p inst/redengine

if [ ! -e inst/redengine/libredengine-1.0.0-rc2.so ]; then
  echo "  cannot find current redatam runtime files"
  echo "  attempting to download them"
  echo "  download.file('$url','redatam-engine.zip',mode='wb')"|${R_HOME}/bin/R --vanilla --slave
  echo "  unpacking current redatam runtime"

  unzip -o -d tmpredatam redatam-engine.zip

  #if [ ! -e tmpredatam/lib/libredengine-1.0.0-rc2.so ]; then
	#    allok=no
	#fi

  cp tmpredatam/lib/libredengine-1.0.0-rc2.* inst/redengine
  rm -rf redatamx-core-linux-latest.zip
  rm -rf tmpredatam
fi

exit 0
