#!/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"

# install code-server
wget https://rstd.io/vs-code-server -O /tmp/vs-code-server.tar.gz
tar zxvf /tmp/vs-code-server.tar.gz --strip 1 -C "$installDirectory"
rm /tmp/vs-code-server.tar.gz

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

# install code-server R and Python extensions
curl -L https://rstd.io/vs-code-python-ext -o ms-python.python-2020.5.86806.vsix.gz && gunzip ms-python.python-2020.5.86806.vsix.gz
./code-server --extensions-dir ./extensions --install-extension ./ms-python.python-2020.5.86806.vsix

curl -L https://rstd.io/vs-code-r-ext -o Ikuyadeu.r-1.1.0.vsix.gz && gunzip Ikuyadeu.r-1.1.0.vsix.gz
./code-server --extensions-dir ./extensions --install-extension ./Ikuyadeu.r-1.1.0.vsix
echo "R extension successfully installed"

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

configContents="enabled=1
exe=$installDirectory/code-server
args=--extensions-dir=$installDirectory/extensions --verbose --disable-updates --host=0.0.0.0"

echo "$configContents" > /etc/rstudio/vscode.conf
echo "/etc/rstudio/vscode.conf generated"
