#!/usr/bin/env bash
# This script manages RStudio's JupyterLab environment

set -e

setJupyterExecutable() {
   exe=$(grep exe $configFile | sed 's/.*\(exe=\)\(.[^ ]*\).*/\2/')
   if [[ -z "$exe" ]]; then
      exe='/usr/local/bin/jupyter' # use default value
   fi
}

# sets global environment variables JLAB_EXT_NAME, JLAB_EXT_VERSION, and JLAB_EXT_VERSION_STRING
# expects to be passed the path to the jupyter executable
setupEnvironment() {
   local jupyterPath="$1"
   if [ -z "${jupyterPath}" ]; then
      jupyterPath=$(setJupyterExecutable)
   fi

   # set jupyterlab global variables
   local versionOutput
   versionOutput="$("${jupyterPath}" lab --version 2>&1)"

   if [[ "$(echo "$versionOutput" | cut -d. -f1)" -ge 4 ]]; then
      export JLAB_EXT_NAME="pwb_jupyterlab"
      export JLAB_EXT_VERSION="1.0"
   else
      export JLAB_EXT_NAME="workbench_jupyterlab"
      export JLAB_EXT_VERSION="1.1"
   fi
   export JLAB_EXT_VERSION_STRING="${JLAB_EXT_NAME}~=${JLAB_EXT_VERSION}"

   # set jupyter notebook global variables
   export JNOTEBOOK_VERSION="$("${jupyterPath}" notebook --version 2>&1)"
}
