#!/bin/sh
# add an ssh key to the list of authorized keys

echo "Paste the key to be added:"
read key

keyfile="$(mktemp)"
echo "$key" > "$keyfile"

# check for errors
fingerprint="$(ssh-keygen -lf $keyfile)"
if [ "$(echo "$fingerprint" | egrep -c '\((R|D)SA|ED25519\)')" -ne "1" ]; then
    echo "Error: $fingerprint"
    rm "$keyfile"
    exit 1
fi

mkdir -p .ssh && \
  echo -n "no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty " >> .ssh/authorized_keys && \
  cat "$keyfile" >> .ssh/authorized_keys

rm "$keyfile"

echo "Success! Added a key with the following fingerprint:"
echo "$fingerprint"
