#!/bin/bash

HOST=`hostname`
REMOTE=$1
USER=$2


SCRIPT=`which $0`

RHOST=`echo ${REMOTE} | awk -F '@' '{print $2}'`



if [ -z ${RHOST} ]
then
	RHOST=${REMOTE}
	RUSER=${USER}
else
	RUSER=`echo ${REMOTE} | awk -F '@' '{print $1}'`
fi

PORT=`echo ${RHOST} | awk -F ':' '{print $2}'`
RHOST=`echo ${RHOST} | awk -F ':' '{print $1}'`

if [ -z "${PORT}" ]
then
	PORT=22
fi

function usage()
{
	echo "Usage: ${SCRIPT} [<remote user>@]<remote address> [<local user>]"
}

if ! [ -z "$QUIET" ]
then
	exec >/dev/null 2>/dev/null
fi

if [ "$1" == "" ]
then
	echo "Error: You must specify the remote address"
	usage
	exit 2
fi

if [ "$3" != "" ]
then
	echo "Error: You have specified more than one remote address"
	usage
	exit 3
fi

if [ -z "$2" ]
then
	USERID=`id -u`
	USER=`id -u -n`
else
	USER=$2
	USERID=`id -u ${USER}`
fi

EXECUSER=`id -u`
if [ "${USERID}" != "${EXECUSER}" ]
then
	if [ "${EXECUSER}" != 0 ]
	then
		echo "Error: If the local user is not the running user, you must be root"
		usage
		exit 4
	fi
fi

LHOME=`cat /etc/passwd | awk -v user=${USER} -F ':' '{if ($1==user) print $6}'`

mkdir -p ${LHOME}/.ssh
chmod 700 ${LHOME}/.ssh
chown ${USER} ${LHOME}/.ssh

KEYSCAN=`ssh-keyscan -p ${PORT} -t rsa ${RHOST}`
if [ -f ${LHOME}/.ssh/known_hosts ]
then
	KEYSCANGREP=`grep "${KEYSCAN}" ${LHOME}/.ssh/known_hosts`
fi

if [ -z "${KEYSCANGREP}" ]
then
	echo ${KEYSCAN} >> ${LHOME}/.ssh/known_hosts
	chown ${USER} ${LHOME}/.ssh/known_hosts
	chmod 600 ${LHOME}/.ssh/known_hosts
else
	echo "Remote public key already in known_hosts file"
fi

if ! [ -f ${LHOME}/.ssh/id_rsa.pub ]
then
	ssh-keygen -N "" -f ${LHOME}/.ssh/id_rsa
	chown ${USER} ${LHOME}/.ssh/id_rsa
	chown ${USER} ${LHOME}/.ssh/id_rsa.pub
else
	echo "Using existing ${LHOME}/.ssh/id_rsa.pub"
fi

ssh-copy-id -p ${PORT} -i ${LHOME}/.ssh/id_rsa.pub ${RUSER}@${RHOST}
