#!/bin/bash
#
# Copyright 2018-2021 Elyra Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
set -euo pipefail

node --version
npm --version

mkdir -p ~/.npm-global
npm config set scripts-prepend-node-path auto
npm config set prefix ~/.npm-global

export PATH=$(pwd)/.npm-global/bin/:$PATH

# Download and install Yarn Package Manager using npm
npm install -g yarn

# Build Elyra Distribution
make release

# Updage dependencies and install Elyra wheel
pip install --upgrade pip
pip install --upgrade --use-deprecated=legacy-resolver tornado jupyter-core jupyter-server jupyterlab dist/*.whl

# Rebuild Jupyter Lab to enable extensions
jupyter labextension link --no-build packages/services/
jupyter labextension link --no-build packages/ui-components/
jupyter labextension link --no-build packages/metadata-common/
jupyter lab build --dev-build=False --minimize=False --debug

mkdir -p binder-demo

# Enable debug output
set -x

# repo2docker clones the Elyra repository before the Docker image is built
# and uses the cloned directory as "root". The git extension recognizes that
# the directory is git-enabled and therefore prevents the user from 
# cloning other repositories using the UI. Remove the git artifacts in the
# root directory to work around this issue. 
rm -rf ~/.git*

# Add getting started assets to Docker image
# (1) Clone the examples repository.
git clone https://github.com/elyra-ai/examples.git 

EXAMPLES_BASE_DIR=examples

# (2) Copy all getting started assets to the working directory,
#     which is referenced when binder is invoked, e.g. 
#     https://mybinder.org/v2/gh/elyra-ai/elyra/master?urlpath=lab/tree/binder-demo
cp -r $EXAMPLES_BASE_DIR/binder/getting-started/* binder-demo/

# (3) Remove the code snippets from the working directory.
#     They need to reside in a different location to be usable.
rm -rf binder-demo/code-snippets

# (4) Add code snippet files to the appropriate location
DATA_DIR=`jupyter --data-dir`
CODE_SNIPPETS_DIR="$DATA_DIR/metadata/code-snippets/"
mkdir -p $CODE_SNIPPETS_DIR
cp $EXAMPLES_BASE_DIR/binder/getting-started/code-snippets/*.json $CODE_SNIPPETS_DIR

# (5) Remove cloned examples directory
rm -rf $EXAMPLES_BASE_DIR
