#!/usr/bin/env bash

#
# install-node
#
# Copyright (C) 2022 Posit Software, PBC
#
# Unless you have received this program directly from Posit Software pursuant
# to the terms of a commercial license agreement with Posit Software, then
# this program is licensed to you under the terms of version 3 of the
# GNU Affero General Public License. This program is distributed WITHOUT
# ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
# AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
#
#

set -e

source "$(dirname "${BASH_SOURCE[0]}")/../tools/rstudio-tools.sh"
section "Installing node"

# check for required ENV vars (as set by install-npm-dependencies)
if ! check_env_vars NODE_VERSION NODE_FOLDER NODE_ROOT NODE_SUBDIR NODE_BASE_URL; then
   exit 1 # check_env_vars has already printed an error message
fi

if [ -f "${NODE_SUBDIR}/bin/node" ]; then
   info "node ${NODE_VERSION} is already installed at '${NODE_SUBDIR}'"
   exit 0
fi

# complete url based on platform
PLATFORM="$(uname)-$(arch)"
case "${PLATFORM}" in

"Darwin-i386")   NODE_FILE="node-v${NODE_VERSION}-darwin-x64" ;;
"Darwin-arm64")  NODE_FILE="node-v${NODE_VERSION}-darwin-arm64" ;;
"Linux-x86_64")  NODE_FILE="node-v${NODE_VERSION}-linux-x64" ;;
"Linux-aarch64") NODE_FILE="node-v${NODE_VERSION}-linux-arm64" ;;
*)
   echo "Node binaries not available for platform '${PLATFORM}'."
   exit 0
;;
esac

# Will be set if we need to use Node 16.
needs-node-16 () {

   # Use Node 16 on Amazon Linux
   if [ -e /etc/os-release ]; then
      . /etc/os-release
      if [ "${ID}" = "amzn" ] && [ "${VERSION_ID}" = "2" ]; then
         return 0
      fi
   fi

   return 1

}

if needs-node-16; then
   NODE_BASE_URL="${RSTUDIO_BUILDTOOLS}/node/v16.20.2/"
   case "$(arch)" in
   aarch64) NODE_FILE="node-v16.20.2-linux-arm64" ;;
   x86_64)  NODE_FILE="node-v16.20.2-linux-x64" ;;
   esac
fi

# build archive paths, etc
NODE_ARCHIVE="${NODE_FILE}.tar.gz"
NODE_URL="${NODE_BASE_URL}${NODE_ARCHIVE}"

# enter node directory
mkdir -p "${NODE_ROOT}"
pushd "${NODE_ROOT}"

# download and extract
echo "Downloading ${NODE_FILE} from ${NODE_URL}"
download "${NODE_URL}" "${NODE_ARCHIVE}"
extract "${NODE_ARCHIVE}"
rm -f "${NODE_ARCHIVE}"

# rename to expected folder name
mv "${NODE_FILE}" "${NODE_FOLDER}"

popd
