#!/usr/bin/env bash
# This script will install Posit's VS Code extension.

set -e

server_bin_dir=/usr/lib/rstudio-server/bin

# eval VSCODE_ARGS to handle ~ or environment variables that might be in --user-data-dir
evaled_vscode_args=$(eval "echo $VSCODE_ARGS")

function help() {
	cat <<EOF
usage: install-vs-code-ext.sh [options]

Install extensions configured in vscode.extensions.conf.
The VS Code binary pointed to by the exe line in vscode.conf or VSCODE_EXEC_COMMAND environment
variable is the VS Code binary that the extension will be installed into.

Examples
   install-vs-code-ext.sh

Options
   -h
         Show this help.
EOF
}


while getopts h: flag
do
    case "${flag}" in
        h)
           help
           exit 0
           ;;
        *)
           echo "Invalid flag: ${flag}"
           exit 1
           ;;
    esac
done

# load and parse vscode config file
configDirs="$XDG_CONFIG_DIRS:/etc"
origIFS=$IFS
IFS=':'; read -ra configDirList <<< "$configDirs"
for configDir in "${configDirList[@]}"
do
   if test -e "$configDir/rstudio/vscode.conf"
   then
      configFile="$configDir/rstudio/vscode.conf"
      break
   fi
done
IFS=$origIFS

# Default to use the code-server executable set by Workbench
# If it's not been set, use the values in vscode.conf instead
# Otherwise exit with an error
if [[ -n "$VSCODE_EXEC_COMMAND" ]]
then
   cs_exe=$VSCODE_EXEC_COMMAND
elif [[ -f "$configFile" ]]
then
   cs_exe=$(grep "^[ \t]*exe" $configFile | sed 's/.*\(exe=\)\(.[^ ]*\).*/\2/')
   if [ -z "$cs_exe" ]; then
      # use the default
      cs_exe="$server_bin_dir/pwb-code-server/bin/code-server"
   fi
   ext_dir=$(grep 'extensions-dir[= ]' $configFile | sed 's/.*\(extensions-dir[= ]\)\(.[^ ]*\).*/\2/')
   if [ ! -z "$ext_dir" ] && [ ! -d "$ext_dir" ]
   then
      echo "$ext_dir does not exist - creating..."
      mkdir $ext_dir
   fi

   if [ -z "$evaluated_vscode_args" ]; then
      evaled_vscode_args=$(grep "^[ \t]*args" $configFile | sed 's/.*\(args=\)\(.*\).*/\2/')
   fi
else
   if [ -z "$POST_INSTALL_SCRIPT" ]; then
      echo "ERROR: Could not install extension. The code-server executable must be set by VSCODE_EXEC_COMMAND or as exe in vscode.conf."
   fi
   exit 1
fi

# read the extension config file to see if we should install any extensions
extFile="$configDir/rstudio/vscode.extensions.conf"
if test -e "$extFile"; then
   echo "Installing extensions from $extFile..."
   while read line
   do
      ext_arg=$(echo "$line" | sed 's/ *$//g')
      if [[ -n "$ext_arg" && ${ext_arg:0:1} != "#" ]]; then
         echo -e '\nRunning command "'$cs_exe' '$evaled_vscode_args' --install-extension '$ext_arg'"...\n'
         echo $ext_arg | xargs $cs_exe $evaled_vscode_args --install-extension
      fi
   done < "$extFile"
else
   echo "Did not locate $extFile, no extensions to install."
fi
