#!/bin/bash
#title           :create_JupyterLab_kernel.sh
#description     :Script to create a spackified JupyterLab kernel conf and place it to NFS where it can be loaded by all users.   
#usage           :./create_JupyterLab_kernel.sh $INSTALLATION_ROOT $ENV $LAB_KERNEL_PATH
#==============================================================================

INSTALLATION_ROOT=$1
SPACKIFIED_ENV=$2
LAB_KERNEL_PATH=$3

# capture the empty env
cd /opt/app-root/src
env >> before.txt

# load spack, spack repos and spack env
cp -r /srv/$INSTALLATION_ROOT/spack/.spack ~
source /srv/$INSTALLATION_ROOT/spack/share/spack/setup-env.sh
spack repo add /srv/$INSTALLATION_ROOT/ebrains-spack-builds
# no need to activate as the env is already activated in the context it is used
#spack env activate $SPACKIFIED_ENV

module use /srv/$INSTALLATION_ROOT/spack/share/spack/modules/linux-centos7-broadwell/
source /srv/$INSTALLATION_ROOT/spack/var/spack/environments/$SPACKIFIED_ENV/loads

# capture the env after spack activation
cd /opt/app-root/src
env >> after.txt

# prepare the env file required for the JupyterLab kernel
mkdir $LAB_KERNEL_PATH/bin
cat <<EOF > $LAB_KERNEL_PATH/bin/env.sh
#!/usr/bin/env bash
set -euxo pipefail
EOF

# load here all tools
#spack load --sh -r python@3.8.11 py-ipykernel py-pip py-numpy@1.21.0 py-scipy py-pandas py-seaborn py-matplotlib arbor nest@3.0 neuron py-pynn tvb-data tvb-library meta-brainscales %gcc@10.3.0 >> $LAB_KERNEL_PATH/bin/env.sh

# append the necessary env variables for spack env and tools
cd /opt/app-root/src
diff before.txt after.txt|grep ">"|cut -c 3- >> $LAB_KERNEL_PATH/bin/env.sh

# end of env creation
cat <<EOF >>$LAB_KERNEL_PATH/bin/env.sh
python -m ipykernel_launcher -f \$@
EOF
chmod +x $LAB_KERNEL_PATH/bin/env.sh
# create the new kernel's configuration file
mkdir $LAB_KERNEL_PATH/spack_python_kernel_release_20210930
cat <<EOF >$LAB_KERNEL_PATH/spack_python_kernel_release_20210930/kernel.json
{
 "argv": ["$LAB_KERNEL_PATH/bin/env.sh", "{connection_file}"],
 "display_name": "EBRAINS_release_v0.1_202109",
 "name": "spack_python_kernel_release_20210930",
 "language": "python"
}
EOF
