#!/bin/bash -l

jupyter_output=$(mktemp ~/.jupyter_output.XXXX)

clean_up() {
        job_id=$(awk '/srun: job/ {print $3;exit}' $jupyter_output)
        scancel $job_id
	rm $jupyter_output
}

trap clean_up EXIT

set -m


if [ x"$PYTHON_VER" = x ]; then
        echo "Please load python and any needed python modules before launching juypter!"
        echo "Example: "
        echo "  enable_lmod"
        echo "  module load python/3.6   # 2.7/3.7 is also avaiable"
        exit 1
fi

echo " * loading jupyter module"

enable_lmod
module load python/$PYTHON_VER
module load jupyter

echo " * launching jupyter notebook server"
(srun -n 1 -c 2 -t 240 -J juypter jupyter-notebook --no-browser --port=$((8000 + $RANDOM % 1000)) --ip=0.0.0.0 2>&1 | tee $jupyter_output > /dev/null) &

echo 
echo "   jupyter server will be on for 4 hour"
echo "   please do not close this window, or jupyter will be terminated immediately"
echo 


sleep 10 

job_id=$(awk     '/srun: job/ {print $3;exit}' $jupyter_output)
tokens=$(awk -F: '/  http:/ {print $3}'        $jupyter_output)
host=$(squeue -j $job_id -O NodeList -h | sed 's/ //g')
url="http://$host:$tokens"

echo " * launching browser"
(firefox $url 2>&1 )>/dev/null &

echo "   if you closed browser, please use below to connect back"
echo "      $url"

wait
