#!/bin/sh -e

##########################################################################
#   Script description:
#       Copy ssh keys to another host.
#       ssh-copy-keys is broken on some systems and may add duplicate keys.
#
#   Arguments:
#       Same as you would use with ssh to the same host.
#
#   Returns:
#       Exit status of ssh command that attempts to install keys.
#
#   History:
#   Date        Name        Modification
#   2014-11-14  Jason Bacon Begin
##########################################################################

usage()
{
    printf "Usage: $0 [ssh flags] remotehost\n"
    exit 1
}


##########################################################################
#   Main
##########################################################################

if [ $# -lt 1 ]; then
    usage
fi

cd

user=`id -un`
host=`hostname`

# Last command-line argument is remote hostname
eval remotehost="\${$#}"

echo "Authorizing ${user}@$host on $remotehost."

cd
if [ ! -f .ssh/id_rsa.pub ] ; then
    if [ ! -e .ssh ]; then
	mkdir .ssh
    fi
    ssh-keygen -P "" -f "./.ssh/id_rsa"
fi

key=`cat .ssh/id_rsa.pub`
# Don't use sed to remove keys since -i syntax is not standardized
ssh $@ "umask 077; mkdir -p .ssh; touch .ssh/known_hosts .ssh/authorized_keys; chmod 600 .ssh/authorized_keys; fgrep -v ${user}@$host .ssh/authorized_keys > .ssh/temp_authorized_keys; mv -f .ssh/temp_authorized_keys .ssh/authorized_keys && echo $key >> .ssh/authorized_keys"
exit $?
