#!/bin/bash --login
# This script sets up SLM Lab for Linux Ubuntu

# Fail on the first error; killable by SIGINT
set -e
trap "exit" INT

echo "--- Installing system dependencies ---"
sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test
sudo apt-get update
sudo apt-get install -y git cmake gcc g++
sudo apt-get install -y zlib1g-dev libjpeg-dev xvfb libav-tools xorg-dev python-opengl libboost-all-dev libsdl2-dev swig build-essential libstdc++6 libhdf5-dev libopenblas-dev

echo "--- Installing NodeJS Lab interface ---"
if which node >/dev/null; then
  echo "Nodejs is already installed"
else
  curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
  sudo apt-get install -y nodejs
  sudo npm install --unsafe-perm=true --allow-root -g yarn
fi

echo "--- Installing npm modules for Lab interface ---"
if [ -d ./node_modules ]; then
  echo "Npm modules are already installed"
else
  yarn install
fi

echo "--- Installing Python for Lab backend ---"
if which python3 >/dev/null; then
  echo "Python3 is already installed"
else
  sudo apt-get -y install python3-numpy python3-dev python3-pip python3-setuptools
fi

echo "--- Installing Conda ---"
if which conda >/dev/null; then
  echo "Conda is already installed"
else
  curl -O https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh
  bash Miniconda3-latest-Linux-x86_64.sh -b
  rm Miniconda3-latest-Linux-x86_64.sh
  echo '. ~/miniconda3/etc/profile.d/conda.sh' >> ~/.bashrc
  source ~/.bashrc
fi

echo "--- Installing Conda environment ---"
if conda env list | grep "^lab " >/dev/null; then
  echo "conda env lab is already installed"
else
  conda create -n lab python=3.6 ipykernel -y
  conda activate lab
  python -m ipykernel install --user --name lab
fi

# remove for reset:
# conda deactivate
# conda env remove -n lab -y
# conda env export > environment.yml
echo "--- Updating Conda environment ---"
conda env update -f environment.yml

# Mac uses box2d-kengz, ubuntu uses box2d
conda activate lab
pip uninstall -y box2d-kengz
pip install box2d

source ~/.bashrc
echo "--- Lab setup complete ---"
