#!/bin/bash

read -e -p "Provide a name for the ssh connection (press enter for '{RUNTIME_CONFIG_NAME}'): " SSH_CONNECTION_NAME; \
if [[ $SSH_CONNECTION_NAME == "" ]]; then SSH_CONNECTION_NAME={RUNTIME_CONFIG_NAME}; fi;

# Check whether the name is valid. Not all names can be used, as for example a ssh config name cannot contain spaces
naming_re='^[a-z0-9_-]+$'

if ! [[ "$SSH_CONNECTION_NAME" =~ $naming_re ]]; then
    echo "[WARNING] The entered name should only contain lowercase characters, numbers and - or _. Please run again and input a valid name.";
    exit 1;
fi

# Create ssh folder in case it does not exist
mkdir -p ~/.ssh && chmod 700 ~/.ssh
touch ~/.ssh/config
touch ~/.ssh/known_hosts

if ! grep -q "Host $SSH_CONNECTION_NAME" ~/.ssh/config; 
then 
    # Setup ssh config information
    echo "
Host $SSH_CONNECTION_NAME
    Hostname {HOSTNAME_RUNTIME}
    Port {PORT_RUNTIME}
    User root
    ServerAliveCountMax 10
    ServerAliveInterval 60
    IdentityFile ~/.ssh/$SSH_CONNECTION_NAME
    #ProxyCommand ssh -W %h:%p -i ~/.ssh/$SSH_CONNECTION_NAME -p {PORT_MANAGER} limited-user@{HOSTNAME_MANAGER}
" >> ~/.ssh/config;

    # Setup private key of runtime
    echo "{PRIVATE_KEY_RUNTIME}" > ~/.ssh/$SSH_CONNECTION_NAME 
    chmod 700 ~/.ssh/$SSH_CONNECTION_NAME
else
    echo "[WARNING] A connection with the name $SSH_CONNECTION_NAME already exists in ~/.ssh/config. Try a different name."
    exit 1
fi;

if ! grep -q "{RUNTIME_KEYSCAN_NAME}" ~/.ssh/known_hosts; 
then 
    echo "{RUNTIME_KNOWN_HOST_ENTRY}" >> ~/.ssh/known_hosts; 
else
    echo "[WARNING] A runtime with the same DNS and Port was already added to known hosts. If the connection test fails, you can try to add 'StrictHostKeyChecking no' to the 'Host $SSH_CONNECTION_NAME' in the ~/.ssh/config";
fi;

# Test the connection
echo "Testing the SSH connection via 'ssh $SSH_CONNECTION_NAME'"
ssh -q $SSH_CONNECTION_NAME exit
if [ $? == 0 ]; then 
    echo "Connection successful!"

    # Setup jupyter remote kernel if remote_ikernel is installed
    if hash remote_ikernel 2>/dev/null; then
        while true; do
            read -p "remote_ikernel was detected on your machine. Do you like to setup a Python remote kernel for Jupyter (yes/no)? " yn
            case $yn in
                [Yy]* ) remote_ikernel manage --add --interface=ssh --kernel_cmd="ipython kernel -f {connection_file}" --name="Py 3.6" --host=$SSH_CONNECTION_NAME; break;;
                [Nn]* ) break;;
                * ) echo "Please answer yes or no.";;
            esac
        done
    fi;

    # Setup SFTP bookmarks in file explorer
    BOOKMARKS_FILE=~/.config/gtk-3.0/bookmarks
    if [ -f "$BOOKMARKS_FILE" ]; then
        # bookmark file detected
        while true; do
            read -p "Do you want to add this connection as mountable SFTP storage to the bookmarks of your file manager (yes/no)? " yn
            case $yn in
                [Yy]* ) printf "\nsftp://$SSH_CONNECTION_NAME/workspace/ $SSH_CONNECTION_NAME" >> $BOOKMARKS_FILE; break;;
                [Nn]* ) break;;
                * ) echo "Please answer yes or no.";;
            esac
        done
    fi

    # TODO Add additional features: e.g. autossh port forwarding for main workspace port, sshfs folder mounting

    # print out some user information
    echo "The ssh configuration is completed successfully. You can now securely connect via 'ssh $SSH_CONNECTION_NAME'.";
else
    echo "[WARNING] Connection test not successful! Please check the ssh setup manually within the ~/.ssh/config"
fi
