#!/usr/bin/env bash

#
# install-yarn
#
# Copyright (C) 2009-20 by RStudio, Inc.
#
# Unless you have received this program directly from RStudio pursuant
# to the terms of a commercial license agreement with RStudio, 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 yarn"

# determine node bin path then prepend to installation path
DEPS_DIR="$(pwd)"
NODE_BIN="${DEPS_DIR}/${NODE_SUBDIR}/bin"
INSTALL_PATH="${NODE_BIN}:${PATH}"

# check for yarn installation
# TODO: do we want to allow yarn installs from other PATH locations?
if command -v yarn 2> /dev/null; then
  YARN_VERSION=$(PATH="${INSTALL_PATH}" yarn --version)
  echo "yarn ${YARN_VERSION} already installed at '${NODE_BIN}/yarn'"
else
  # download the yarn installer
  YARN_INSTALL_URL="https://yarnpkg.com/install.sh"
  YARN_INSTALL_SCRIPT="yarn-install.sh"
  download "${YARN_INSTALL_URL}" "${YARN_INSTALL_SCRIPT}"

  # run the installer script
  chmod +x "${YARN_INSTALL_SCRIPT}"
  PATH=${INSTALL_PATH} ./"${YARN_INSTALL_SCRIPT}"
  rm "${YARN_INSTALL_SCRIPT}"

  # update INSTALL_PATH
  INSTALL_PATH="${HOME}/.yarn/bin:${HOME}/.config/yarn/global/node_modules/.bin:${INSTALL_PATH}"
fi

# install panmirror dependencies
if [ -d "/opt/rstudio-tools/panmirror" ]; then
  # install dependencies from /opt/rstudio-tools if present
  pushd /opt/rstudio-tools/panmirror
else
  # otherwise, use source tree
  pushd ../../src/gwt/panmirror/src/editor
fi

PATH=${INSTALL_PATH} yarn config set ignore-engines true
PATH=${INSTALL_PATH} yarn install

popd
