#!/bin/bash

echo "UID: $UID XDG_RUNTIME_DIR: $XDG_RUNTIME_DIR USER: $USER DISPLAY: $DISPLAY"

{ [[ 0 -ge "0$UID" ]] || [[ -z "${XDG_RUNTIME_DIR}" ]] || [[ -z "${USER}" ]] || [[ -z "${DISPLAY}" ]] ; } && { echo "Least one environment variable has incorrect value!" 1>&2 ; exit 1 ; }

useradd -d /home/${USER} -s /bin/bash -u ${UID} ${USER}

BASEDIR=/home/${USER}/prednasky
#BASEDIR=/builds/pb176/private/prednasky
mkdir -p /home/${USER}/prednasky
mkdir -p /home/${USER}/.local/bin /home/${USER}/.jupyter
ln -s $BASEDIR/ci-overrides/bin/jupyter-notebook /home/${USER}/.local/bin/jupyter-notebook

test -f /home/${USER}/.gitconfig-base && cat /home/${USER}/.gitconfig-base >> /home/${USER}/.gitconfig

if [[ -n "$GITLAB_CREDENTIALS" ]] && ! [[ -f /home/${USER}/.git-credentials ]] ; then
	git config --file "/home/${USER}/.gitconfig" credential.helper store
	printf "https://%s@gitlab.fi.muni.cz/\n" "${GITLAB_CREDENTIALS}" >> /home/${USER}/.git-credentials
	chmod 600 /home/${USER}/.git-credentials
fi

chown -R ${USER} /home/${USER}/.local /home/${USER}/.jupyter /home/${USER}/.gitconfig /home/${USER}/.git-credentials
chown ${USER} /home/${USER}/

if [[ "$1" = "bash" ]] || [[ -x "$1" ]] ; then
	exec "$@"
fi

PASSWORD=""
SECURITY="--NotebookApp.token= --NotebookApp.password="

if [[ "$1" = "--" ]] ; then
	PASSWORD="$1"
	shift 2
elif [[ -n "$JUPYTER_CREDENTIALS" ]] ; then
	PASSWORD="$JUPYTER_CREDENTIALS"
fi

if [[ -n "$PASSWORD" ]] ; then
	SECURITY="--NotebookApp.password=$(/usr/bin/python3 -c "from notebook.auth import passwd ; print(passwd('$PASSWORD'));")"
fi

cd $BASEDIR
tmux new-session -s notebook sudo -u ${USER} env PATH=$PATH /usr/local/bin/jupyter-notebook --ip 0.0.0.0 $SECURITY "$@"
