#!/usr/bin/env bash

set -eu

export NODE_VER="v12.16.1"

echo "Setting up common dependencies for CDv3 development..."

SCRIPT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
COREDASH_ROOT="$SCRIPT_ROOT/.."
SPECTRUM_ROOT="$COREDASH_ROOT/../.."
DRIVING_ROOT="$SPECTRUM_ROOT/.."

MAX_RETRIES=3
YARN_INSTALL="yarn install --frozen-lockfile --mutex file:$DRIVING_ROOT/yarn.mutex"

# Simple wrapper for `yarn install` that retries it if it fails.
yarn_install () {
  retries=1
  while ! eval $YARN_INSTALL
  do
    ((retries++))
    if [ $retries -gt $MAX_RETRIES ]
    then
      echo "\nyarn install failed after $retries retries"
      exit 1
    else
      echo "\nretrying yarn install, attempt: $retries"
    fi
  done
}

cd $COREDASH_ROOT

echo "Installing nvm..."

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.2/install.sh | bash

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

echo "Installing node version ${NODE_VER}"
nvm install $NODE_VER
echo "Using node version ${NODE_VER}"
nvm use $NODE_VER

echo "Using node version..."
node --version

npm install -g yarn

echo "Generating gRPC & protos..."
(cd $SPECTRUM_ROOT/scripts; ./generate_protos.py)
# Skips the preinstall script in Spectrum UI which rebuilds tsprotos.
export SKIP_SPECTRUMUI_TSPROTOS_PREINSTALL=true

echo "Installing and building bobjs"
cd $SPECTRUM_ROOT/bobjs
yarn_install
yarn build

echo "Installing and building linkclient"
cd $SPECTRUM_ROOT/linkclient
yarn_install
yarn build

echo "Installing & building tsprotos"
cd $SPECTRUM_ROOT/tsprotos
yarn_install

echo "Installing @zoox/worker"
cd $DRIVING_ROOT/mapping/zrn/web_viewer/worker/
yarn_install
yarn build

echo "Installing three_zrn"
cd $DRIVING_ROOT/mapping/zrn/web_viewer/three_zrn/
yarn_install
yarn build

echo "Installing spectrum3d"
cd $SPECTRUM_ROOT/spectrum3d
yarn_install
yarn build

echo "Installing spectrum-ui"
cd $SPECTRUM_ROOT/spectrum-ui
yarn_install
yarn build

echo "Building CoreDash v3..."
cd $COREDASH_ROOT

echo "Installing yarn dependencies for CoreDash (last step)"
yarn_install
