#!/bin/bash

# Download an ssh key, and add it to the users authorized_keys file

# ask for user when not on commandline
if test "$1" = ""; then
  read -p "Name of the user: " user
else
  user=$1
fi
if test "$user" = ""; then
  echo "no username, I stop!"
  exit 1
fi

# test if user excists:
if test "$(id -u $user 2>/dev/null)" = ""; then
   echo "user $user does not excist, I stop"
   exit 2
fi

# ask for the key
if test "$2" = ""; then
  read -p "Please give the URL of the pubkey: " url
else
  url=$2
fi
if test "$url" = ""; then
  echo "no url, I stop!"
  exit 3
fi

cd /home/$user/.ssh                            # go to the user's .ssh directory
wget $url -O /tmp/key                          # download user's public key, and save it
cat /tmp/key >> authorized_keys                # add the key to the authorized_keys file
chown $user:$user authorized_keys              # change the ownership of the file
chmod 600 authorized_keys                      # change the rights of the file
rm /tmp/key                                    # clean-up


