#!/bin/bash
unset DISPLAY
if [ $# -ge 1 ]; then
    echo Usage: $0
    echo Environment variable JUPYTER_PATH points to the top directory
    echo of jupyter, default: /usr/local/bin/jupyter
    echo
    echo Environment variable CONDA_ROOT_PATH points to the top directory
    echo of conda, e.g. /share/apps/anaconda3, default: NULL
    echo
    echo Environment variable CONDA_ENV_NAME points to the conda enviroment
    echo of jupyter, default: NULL
    echo
    echo Environment variable CONTAINER_PREFIX. Singularity command prefix
    echo to run the code server. e.g.
    echo export CONTAINER_PREFIX="singularity run --pid -B /opt,/lib64,/usr,/share,/etc/profile.d,/etc/ld.so.cache --env PATH=/usr/bin:/opt/skyformai/bin /share/apps/containers/rocky8.sif"
    exit 1
fi

if [ -z $CB_JOBID ] || [ -z "$CB_ALLOCATION" ]; then
    echo Please submit the script as an AIP job.
    exit 1
fi

if [ -z $JUPYTER_PATH ]; then
    jupyter=/usr/local/bin/jupyter
else
    jupyter=$JUPYTER_PATH
fi
cd $HOME
jupyter_workdir=$HOME/.jupyter
if [ ! -d $jupyter_workdir ]; then
    mkdir $jupyter_workdir
    if [ $? != 0 ]; then
       echo 'ERROR: Cannot write to user home directory.'
       exit 1
    fi
fi

# delete log files older than 30 days
find $jupyter_workdir -type f -name '*.log' -mtime +30 -exec rm "{}" \;
find $jupyter_workdir -type f -name '*.sh' -mtime +30 -exec rm "{}" \;

export XDG_RUNTIME_DIR=$jupyter_workdir
port=`echo $CB_ALLOCATION | awk -F '"Port":' '{print $2}' | cut -d'}' -f1 | cut -d, -f1`
#ip=$(hostname -I | awk {'print $1}')
if netstat -nlp 2> /dev/null | grep -q $port; then
    port=$((port+100))
fi
ip=$(grep $(hostname -s) $CB_ENVDIR/hosts | awk '{print $1}')
if grep -q ^pp $CB_ENVDIR/vncsub.yaml; then
    webroot="/ajj/$ip/$port"
    webparam="--ServerApp.base_url=$webroot"
else
    webroot="http://$ip:$port"
    webparam=""
fi

logfile=$jupyter_workdir/session$CB_JOBID.log
export SINGULARITYENV_PS1="[\u@\h \W]\$ "
# job %1
launchfile=$jupyter_workdir/runjupyter.$CB_JOBID.sh
echo "#!/bin/bash" >  $launchfile
if [ ! -z $CONDA_ROOT_PATH ]; then
   echo "source $CONDA_ROOT_PATH/etc/profile.d/conda.sh" >> $launchfile
fi
if [ ! -z $CONDA_ENV_NAME ]; then
   echo "conda activate $CONDA_ENV_NAME" >> $launchfile
fi
echo "$CONTAINER_PREFIX $jupyter lab --ip=$ip --port=$port $webparam --ServerApp.allow_origin='*' $@ > $logfile 2>&1 " >> $launchfile
/bin/bash $launchfile &

# The following is for Parallel Ipython. Disabled for now.
n=1
while true;do
  sleep 1
  token=`grep "       http" $logfile | awk -F "lab" '{print $2}' | head -1`
  if [ "_$token" != "_" ] || [ $n == 120 ]; then
    break
  fi
  n=$((n+1))
done
if [ "_$token" == "_" ]; then
  kill %1
  exit -1
fi
message="$webroot/lab$token"
cpost -d "$message" $CB_JOBID 2>&1 > /dev/null 2>&1 > /dev/null
while true; do
  sleep 2
  jobs %1 | grep Running 2>&1 > /dev/null
  if [ $? != 0 ]; then
    exit 0
  fi
done
