#!/usr/bin/env bash

# Installs yarn if it isn't already installed.

set -euo pipefail

# Set up some variables
APP_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DRIVING_ROOT="$APP_ROOT/.."
SPECTRUM_ROOT="$DRIVING_ROOT/spectrum"

export NODE_VER=$(<$APP_ROOT/.nvmrc)
export NVM_DIR="$HOME/.nvm"
export NVM_SH="$NVM_DIR/nvm.sh"

sudo () {
  # if root, don't use sudo
  [[ $EUID = 0 ]] || set -- command sudo "$@"
  "$@"
}

# Install and setup NVM
if [ ! -e $NVM_DIR -o ! -e $NVM_SH ]; then
    sudo apt update
    sudo apt install -y build-essential curl unzip
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash
fi

# Activate nvm, but prevent nvm error from causing later steps to exit
set +e
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
set -e

# Install and setup Node
if ! nvm use $NODE_VER &> /dev/null ; then
    nvm install $NODE_VER
    nvm use $NODE_VER
fi
node --version

# Install yarn
npm install -g yarn

# Update packages, and ensure yarn is installed
if ! hash yarn > /dev/null 2>&1; then
  curl --silent --show-error https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
  echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
  sudo apt-get update
  sudo apt-get install --assume-yes yarn
fi
