# This script will be called by the canopener
# After canopener has installed git and cloned the purple repository

# PARSE ARGS
while getopts ":u:p:e:" opt; do
  case $opt in
    u) USER="$OPTARG"
    ;;
    p) PASS="$OPTARG"
    ;;
    e) EMAIL="$OPTARG"
    ;;
    \?) echo "Invalid option -$OPTARG" >&2
    ;;
  esac
done


cd ~

# Install dependencies
sudo apt-get update
sudo apt-get install -y curl git build-essential libudev-dev

DISTRO=$(ls /etc/apt/sources.list.d | grep barco | sed "s/barco-nrc\.\([a-zA-Z0-9]*\)\.list/\1/" )
if [[ "${DISTRO}" = "giles" ]]; then
	sudo apt-get install -y base64
fi

# STOP RUNNING SERVICES
sudo service barco-edu-proxy stop
sudo systemctl disable barco-edu-proxy

# SETUP NPM
NPM_AUTH=$(curl -X GET -u $USER:$PASS https://bin.barco.com/artifactory/api/npm/auth)
IFS=' ' read -r -a array <<< "$NPM_AUTH"
BASIC_AUTH_B64=${array[2]}
BASIC_AUTH=$(echo $BASIC_AUTH_B64 | base64 --decode)

echo "registry = https://bin.barco.com/artifactory/api/npm/npm-virtual" > ~/.npmrc
echo "$NPM_AUTH">>~/.npmrc
echo "electron_mirror=https://$BASIC_AUTH@bin.barco.com/artifactory/www-cache/edu-electron/">>~/.npmrc

# SETUP NODE
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh > ~/install.sh
chmod +x ~/install.sh
bash ~/install.sh
export NVM_DIR="/home/barco/.nvm" && [ -s"$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
nvm install 14
nvm alias default 14
rm ~/install.sh

# Configure X
sudo sed -i 's/\-nocursor//' /lib/systemd/system/startx.service
sudo rm /root/.Xmodmap
sudo systemctl daemon-reload
sudo systemctl restart startx.service

# NPM install purple
cd ~/edu/purple
export ELECTRON_MIRROR="https://$BASIC_AUTH@bin.barco.com/artifactory/www-cache/edu-electron/"
npm run barco:install
bash ./sandbox.sh