#!/usr/bin/env bash

set -euo pipefail

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 "$@"
  "$@"
}


# nvm setup
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 dev_setup.sh script to exit
set +e
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
set -e

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

# yarn setup
npm install -g yarn

# if needed, install python 3.6
if ! python3.6 --version &> /dev/null ; then
  echo "installing python3.6"
  sudo apt install -y software-properties-common apt-transport-https
  sudo add-apt-repository -y ppa:deadsnakes/ppa
  sudo apt update
  sudo apt install -y python3.6
fi

# yarn install, inside function for retries
$APP_ROOT/install_yarn_with_retries.sh

# proto_ui_gen setup
echo "installing proto_ui"
$APP_ROOT/scripts/proto_ui_gen/run.sh
