#!/usr/bin/env bash

#
# install-npm-dependencies
#
# 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"

# ensure required environment variables
if ! check_env_vars RSTUDIO_BUILDTOOLS RSTUDIO_NODE_VERSION RSTUDIO_INSTALLED_NODE_VERSION; then
   exit 1
fi

function install-node() {

   # set up node variables common to scripts
   export NODE_VERSION="${1}"
   export NODE_FOLDER_SUFFIX=""
   export NODE_INSTALL_TYPE="${2}"

   if [ "${NODE_INSTALL_TYPE}" == "installed" ]; then
      export NODE_FOLDER_SUFFIX="-installed"
   fi

   export NODE_FOLDER="${NODE_VERSION}${NODE_FOLDER_SUFFIX}"
   export NODE_ROOT="node"
   export NODE_SUBDIR="${NODE_ROOT}/${NODE_FOLDER}"
   export NODE_BASE_URL="${RSTUDIO_BUILDTOOLS}/node/v${NODE_VERSION}/"

   # special case for building on Apple arm64: install x64 node in the 
   # default location (so GWT build can easily find it), but also a
   # separate arm64 node install (for the Electron build to use)
   if is-m1-mac; then
      export NODE_FOLDER="${NODE_VERSION}-arm64${NODE_FOLDER_SUFFIX}"
      export NODE_SUBDIR="${NODE_ROOT}/${NODE_FOLDER}"
   fi

   ./install-node

   if [ "${NODE_INSTALL_TYPE}" == "installed" ]; then
      # Only keep the `node` binary to reduce size and security footprint.
      find "${NODE_SUBDIR:?}" -mindepth 1 -not -path "${NODE_SUBDIR:?}/bin/node" -not -path "${NODE_SUBDIR:?}/bin" -delete
   fi
}

# the version of node.js that gets installed with the product
install-node "${RSTUDIO_INSTALLED_NODE_VERSION}" installed

# the version we use for building product components
install-node "${RSTUDIO_NODE_VERSION}"

# install yarn
case "$(uname -sm)" in
"Linux aarch64") ./install-yarn-linux-aarch64 ;;
*)               ./install-yarn               ;;
esac

