#!/usr/bin/env bash

CYLC_LATEST_VERSION=$(cylc list-versions | grep "^[0-9]" | sort -r | head -n 1)

# export the correct environment variables to the users bashrc file
grep -q 'export PROJECT=nesi00213' ~/.bashrc || echo 'export PROJECT=nesi00213' >>~/.bashrc
grep -q "export CYLC_VERSION=$CYLC_LATEST_VERSION" ~/.bashrc || echo "export CYLC_VERSION=$CYLC_LATEST_VERSION" >>~/.bashrc
test -d ~/cylc-src -a -d ~/cylc-run || mkdir ~/cylc-src ~/cylc-run

# If the user does not already have an ssh key generated on NeSI login
# nodes, then we must do so.
if ! compgen -G "$HOME/.ssh/id_*.pub" >/dev/null; then
    echo "You are about to be prompted for an ssh key password."
    echo "You must hit enter (twice) to ensure the key does not have one."
    sleep 1
    ssh-keygen
fi

# In order for cylc to manage jobs via SSH it needs password-less
# login via SSH, we do that by authorizing the local SSH keys to
# login.

cat ~/.ssh/id_*.pub >>~/.ssh/authorized_keys

# These permissions must be set for the ssh keys to work.
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_*
chmod 644 ~/.ssh/id_*.pub
chmod 750 ~

# Jupyter Notebook Setup
mkdir -p ~/.cylc/uiserver
# Beginning with port=21300, so we don't try to give a user a
# privileged port, find a port that is unique among nesi00213 project
# members. Configure cylc to host the gui on that port. The port needs
# to be unique because users will port-forward this port when they
# connect to the jupyter lab notebook upon executing cylc gui.
if ! grep -q "$USER=" /nesi/nobackup/nesi00213/cylc_port_maps; then
    NEXT_WORKFLOW_PORT=$(awk -F= 'BEGIN{port=21299} { if ($2>port) port=$2 fi } END {print port + 1}' /nesi/nobackup/nesi00213/cylc_port_maps)

    cat <<EOF >~/.cylc/uiserver/jupyter_config.py
c.ServerApp.open_browser=False
c.ServerApp.port=$NEXT_WORKFLOW_PORT
EOF
    # Record the cylc port map so that the next user can find a unique
    # port for themselves.
    echo "$USER=$NEXT_WORKFLOW_PORT" >>/nesi/nobackup/nesi00213/cylc_port_maps
else
    NEXT_WORKFLOW_PORT=$(grep "$USER=" /nesi/nobackup/nesi00213/cylc_port_maps | cut -d= -f2)
fi

cat <<EOF
You are correctly setup for Cylc $CYLC_LATEST_VERSION.
Check that your ssh configuration is working correctly by executing on mahuika:

	ssh mahuika02 echo Hello from Mahuika02

If this command does not prompt for a password, you are good to go.

To connect to cylc gui run:

On mahuika:
	cylc gui

Take note of the url cylc asks you to copy and paste, the one with "127.0.0.1" in the output. It will look something like:

	http://127.0.0.1:$NEXT_WORKFLOW_PORT/cylc?token=99122750aca901546a5d10ffc2d65b27

but your token will vary.

On your machine:
	ssh -N -L $NEXT_WORKFLOW_PORT:localhost:$NEXT_WORKFLOW_PORT mahuika

Then open the url cylc asked you to copy and paste earlier.
EOF
