#!/bin/bash

# =================
# = SSH Key Setup =
# =================

# This code is licensed under the GPLv3 License, available at http://www.gnu.org/licenses/gpl-3.0.txt
# Basically this means you can do whatever you want to it, except sell it or close the source
# Also, I take no responsibility if this script borks your system or sends the private key to some hacker in China.
# It's not that complicated, so read it over before you run it to make sure it's not doing anything weird.

function quit {
	if [ ! -z $1 ]
		then echo $1;
	fi
	echo "Exiting script...";
	exit 192;
}

function usage {
	echo "Usage:";
	echo " 1 - Remote host";
	echo " 2 - Username on remote host (defaults to your current username)";
	echo " [3 - Path to save the key to (Optional, defaults to ~/.ssh/)]";
	quit;
}


if [ -z $1 ]
	then usage;
fi

server=$1

if [[ -z $2 ]]; then
	username=`whoami`;
else
	username=$2
fi

if [ -z $3 ]
	then path=~/.ssh/
else
	path=$3
fi

if [ ! -d ${path} ]
	then if ! mkdir ${path}
		then quit "Couldn't create ${path}";
	fi
fi

if !(ping -q -c 1 $server > /dev/null)
	then quit;
fi

if (cat ${path}${server}_dsa.pub | ssh ${username}@${server} 'cat - >> ~/.ssh/authorized_keys') ; then
	ssh-keygen -t dsa -f ${path}${server}_dsa -C "${username}@${server}"
	chmod 600 ${path}${server}_dsa;
	echo "Host ${server}" >> ~/.ssh/config
	echo "IdentityFile ${path}${server}_dsa" >> ~/.ssh/config
	cat ${path}${server}_dsa.pub | ssh ${username}@${server} 'cat - >> ~/.ssh/authorized_keys'
	rm ${path}${server}_dsa.pub
	echo "alias ${server}='ssh ${username}@${server}'" >> .bash_profile
else
	rm ${path}${server}_dsa.pub
	rm ${path}${server}_dsa
	quit "Couldn't copy to remote server"
fi
