#!/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;

##core engine version
engine_version="1.1.0-final"
engine_file="libredengine-$engine_version"

URL="https://redatam-core.s3.us-west-2.amazonaws.com/core-dev/$redatamurl/redatamx-core-$redatamurl-$engine_version.zip"
DEST="redatam-engine.zip"

echo "using download from '$URL'"

echo "checking REDATAM libraries"

allok=yes

mkdir -p inst/redengine

if [ ! -e inst/redengine/$engine_file ]; then
  echo "cannot find current redatam runtime files"
  echo "attempting to download them"
  echo "download.file('$URL','$DEST',mode='wb')"|${R_HOME}/bin/R --vanilla --slave

  if [ -f $DEST ]; then
    echo "unpacking current redatam runtime"
    unzip -o -d tmpredatam redatam-engine.zip

    cp tmpredatam/release/lib/$engine_file.* inst/redengine
    rm -rf redatamx-engine.zip
    rm -rf tmpredatam
  else
    echo "Can't download file '$URL', compilation compilation continue without runtime"
    #exit 1
  fi

fi

exit 0
