#!/bin/sh
# September 23, 2003 (initial) 
# Updated August 23, 2006 (updated)
#
# Steve Thielemann
# 
# A script file to add ssh key
#
# 1.) Verifies ~/.ssh directory exists, if not creates and
#     fixes permissions.
# 2.) Verifies ~/.ssh/authorized_keys exists, if not creates and
#     fixes permissions.
# 3.) Checks to see if ssh key is already present, if not adds to
#     ~/.ssh/authorized_keys.
#
# dependant on:  grep, touch, chmod, cut
#

if [ -z $1 ]
then
	echo "I need the filename of a public key to add."
	echo "(The .pub file created from ssh-keygen -t rsa)"
	echo "Example:  $0 remote_rsa.pub"
	exit
fi

if [ -f $1 ]
then
	keyid=`cut -f3- '-d ' < $1`
else
	echo "I can't find $1 !"
	exit
fi

echo "Using ID $keyid"

# variables to make life easier

sshdir=~/.ssh
keyfile=~/.ssh/authorized_keys

if [ ! -d "$sshdir" ] 
then
echo "Making $sshdir"
mkdir "$sshdir"
chmod 700 "$sshdir"
fi

if [ ! -f "$keyfile" ]
then
echo "Creating $keyfile"
touch "$keyfile"
chmod 644 "$keyfile"
fi

grep "$keyid" "$keyfile" > /dev/null
if [ $? = 1 ]
then
echo "Adding key to $keyfile"
cat $1 >> "$keyfile"
else
echo "Key $keyid already present."
fi

# the end

