#!/usr/bin/env bash

set -e

# ensure installation directory is specified
if [ -z "$1" ]
then
   echo "error: must specify directory where code-server will be installed"
   exit 1
fi

installDirectory=$(readlink -f "$1")

# ensure installation directory exists and has necessary permissions
mkdir -p "$installDirectory"

dirPermissions=$(stat -c '%a' "$installDirectory")
userPermissions=${dirPermissions:0:1}
groupPermissions=${dirPermissions:1:1}
othersPermissions=${dirPermissions:2:1}

case "$userPermissions" in
   5) userPermsBad=false ;;
   7) userPermsBad=false ;;
   *) userPermsBad=true ;;
esac

case "$groupPermissions" in
   5) groupPermsBad=false ;;
   7) groupPermsBad=false ;;
   *) groupPermsBad=true ;;
esac

case "$othersPermissions" in
   5) othersPermsBad=false ;;
   7) othersPermsBad=false ;;
   *) othersPermsBad=true ;;
esac

if $userPermsBad || $groupPermsBad || $othersPermsBad
then
   if ! chmod a+rx "$installDirectory"
   then
      echo "Could not set permissions on installation directory $installDirectory - ensure they are at least 555 (all users must be able to read and traverse the directory)" 
      exit 1
   fi
fi

cd "$installDirectory"

# clean up any existing version libraries
if [[ -e $installDirectory/lib/vscode/node_modules ]]
then
  rm -rf $installDirectory/lib/vscode/node_modules
fi

# install code-server
curl -L https://rstd.io/vs-code-server-3-9-3 -o "/tmp/vs-code-server-3.9.3.tar.gz"
tar zxvf "/tmp/vs-code-server-3.9.3.tar.gz" --strip 1 -C "$installDirectory"
rm "/tmp/vs-code-server-3.9.3.tar.gz"

echo "code-server installed at $installDirectory/code-server"

# determine 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
if [[ $configFile == "" ]]
then
   configFile="/etc/rstudio/vscode.conf"
fi

# update vs code / RSP configuration
REGENERATE_VSCODE_CONF=true
if [ -f $configFile ]
then
   while true; do
      read -p "The VSCode configuration file $configFile already exists - do you wish to regenerate it (y or n)? " yn
      case $yn in
         [Yy]* ) REGENERATE_VSCODE_CONF=true; break;;
         [Nn]* ) REGENERATE_VSCODE_CONF=false; break;;
         * ) echo "Invalid input - please input either yes or no";;
      esac
   done
fi

if [ "$REGENERATE_VSCODE_CONF" = true ]; then
   configContents="enabled=1
exe=$installDirectory/bin/code-server
args=--verbose --host=0.0.0.0 ${@:2}"

   echo "$configContents" > $configFile
   chmod 644 $configFile
   echo "$configFile generated"
else
  # update config to remove outdated code-server flag we set prior to Juliet Rose
  sed -iE "s|--disable-updates[ ]\?||" $configFile

  # code-server move the executable to /bin in 3.3.0
  # in case we are updating code-server, determine if the exe needs to be updated
  cs_exe=$(grep exe $configFile | sed 's/.*\(exe=\)\(.[^ ]*\).*/\2/')
  if [[ $cs_exe != */bin/* ]]
  then
     orig_cs_exe="$cs_exe"
     cs_exe=$(dirname $cs_exe)/bin/code-server
     sed -i "s|$orig_cs_exe|$cs_exe|" $configFile
  fi
fi

REGENERATE_VSCODE_USER_SETTINGS=true
if [ -f "/etc/rstudio/vscode-user-settings.json" ]
then
   while true; do
      read -p "The VSCode user settings json configuration file /etc/rstudio/vscode-user-settings.json already exists - do you wish to regenerate it (y or n)? " yn
      case $yn in
         [Yy]* ) REGENERATE_VSCODE_USER_SETTINGS=true; break;;
         [Nn]* ) REGENERATE_VSCODE_USER_SETTINGS=false; break;;
         * ) echo "Invalid input - please input either yes or no";;
      esac
   done
fi

if [ "$REGENERATE_VSCODE_USER_SETTINGS" = true ]; then
   userSettingsContents="{
      \"terminal.integrated.shell.linux\": \"$SHELL\",
      \"extensions.autoUpdate\": false,
      \"extensions.autoCheckUpdates\": false
}"
   
   echo "$userSettingsContents" > /etc/rstudio/vscode-user-settings.json
   chmod 644 /etc/rstudio/vscode-user-settings.json
   echo "/etc/rstudio/vscode-user-settings.json generated"
fi

if [[ "${@:2}" =~ "--extensions-dir" ]]
then
   rstudio-server install-vs-code-ext -d "$1"
fi
