#!/bin/bash

if [[ -z "$DOCKER_IP" && -z "$1" ]]; then
    echo "You must either be docked, or provide a argument specifying the 'moniker' of the dock you want to run your notebook against"
    exit -1
fi

if [ -n "$1" ]; then
    # Look up IP from moniker
    FOUND_MONIKER=false
    for f in $HOME/.docker/*; do
        if [ -d $f ] && [ -f $f/connection_config.txt ]; then
          while read -r line; do declare $line; done < "$f/connection_config.txt"
          if [ $DOCK_MONIKER = $1 ]; then
            FOUND_MONIKER=true
            break
          fi
        fi
    done

    if [ $FOUND_MONIKER = false ]; then
      echo "Can't find dock configuration for $1"
      exit -1
    fi
    DOCKER_IP=$DOCK_IP
fi

SSH_OPTIONS="-o LogLevel=error -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
echo "Starting Jupyter on ${DOCKER_IP}"

ssh ${SSH_OPTIONS} ubuntu@$DOCKER_IP 'jupyter lab >~/jupyter.out 2>&1 &'

echo "Waiting for Jupyter to start... (20s)"
sleep 20
open "http://$DOCKER_IP:8888/lab"
