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

set -e

export JLAB_EXT_VERSION=1.1.1
export JLAB_EXT_NAME="workbench_jupyterlab"

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

echoInstallWarning() {
   echo -e "\nWARNING A Posit Workbench Extension has been developed for JupyterLab. To install the extension, run the following command from wherever sessions will run. Be careful to use the version of pip used by the Jupyter environment configured in $configFile, and you most likely must run the command with sudo:
   sudo pip install ${JLAB_EXT_NAME}"
}

echoUninstallOldVersionWarning() {
   echo -e "\nWARNING An outdated vesion of the Jupyterlab extension has been discovered on your system. This version should be removed and the extension should be reinstalled following the instructions above. To remove the extension, use the version of pip used by the Jupyter environment configured in $configFile, and use sudo if necessary:
   sudo pip uninstall ${OLD_JLAB_EXT_NAME}"
}

# the extension used a different name prior to its official release, if this version is installed
# we need to warn the user of the name change
export OLD_JLAB_EXT_NAME="jupyterlab_rsw"

testForOldExtension() {
   if [ -z "$exe" ]; then
      setJupyterExecutable
   fi

   if [ "$(echo $(${exe} labextension list 2>&1) | grep -c ${OLD_JLAB_EXT_NAME})" -eq 1 ]; then
      echoUninstallOldVersionWarning
   fi
}

newExtensionNotification() {
   # load and parse jupyter config file
   configDirs="$XDG_CONFIG_DIRS:/etc"
   IFS=':' read -ra configDirList <<< "$configDirs"
   for configDir in "${configDirList[@]}"
   do
      if test -e "$configDir/rstudio/jupyter.conf"
      then
         configFile="$configDir/rstudio/jupyter.conf"
         break
      fi
   done
   
   # exit if Jupyter is not configured
   if [ ! -f "$configFile" ]; then
      exit 0
   fi
   
   # exit if JupyterLab not enabled
   jlab_enabled=$(grep labs-enabled $configFile | sed 's/.*\(labs-enabled=\)\(.[^ ]*\).*/\2/')
   if [[ -z ${jlab_enabled} || ${jlab_enabled} != 1 ]]; then
      exit 0
   fi
   
   setJupyterExecutable
   
   # the executable may not exist here, but since JupyterLab is enabled we still display the warning
   if [ ! -f "$exe" ]; then
      echoInstallWarning
      exit 0
   fi
   
   if [ "$(echo $(${exe} labextension list 2>&1) | grep -c ${JLAB_EXT_NAME})" -lt 1 ]; then
      echoInstallWarning
   fi
 
   testForOldExtension

   exit 0
}

