#!/usr/bin/env bash

set -euo pipefail

echo "Welcome to PipeDream"
echo ""
read -p "Please enter your cluster user, or leave empty to use system username: " user
echo ""

user="${user:-"$USER"}"
host=slurm-primary.zooxlabs.com

if [ -e "$HOME/.pipedream/$user.key" ]; then
  echo "Keyfile exists for $user, regenerate?"
  select yn in "Yes" "No"; do
    case "$yn" in
      Yes ) break ;;
      No ) exit ;;
    esac
  done
  echo ""
fi

echo "Generating your cluster credential keypair..."
echo ""
mkdir --parents $HOME/.pipedream/
ssh-keygen -t rsa -f "$HOME/.pipedream/$user.key" -N ""
echo ""


echo "Provisioning 2180 cluster with your new keypair..."
echo ""

echo "Please enter your cluster password"
ssh "$user@$host" 'mkdir -p .ssh && touch $HOME/.ssh/authorized_keys chmod 0640 $HOME/.ssh/authorized_keys'
echo ""
echo "Please re-enter your cluster password"
cat "$HOME/.pipedream/$user.key.pub" | ssh "$user@$host" 'cat >> ~/.ssh/authorized_keys'
chmod 0600 "$HOME/.pipedream/$user.key"
echo ""

echo "All set. You should not need to run this again."
echo "You can now log in to the cluster with:"
echo ""
echo "  ssh -i $HOME/.pipedream/$user.key $user@$host"
echo ""
