#!/bin/bash
# Process CLI arguments to set up assumptions.
searchterm="$1"
if [ -z "$searchterm" ]; then searchterm="'*'"; fi
###
### Sets up key-based auth to remote hosts and replicate local .bashrc and .profile to them.
### Assumes that
###
### (Assumed) term to search for as a prefix
### (Assumed) system .ssh/config hostname
### (Assumed) system real hostname
function push() {
tput setaf 2; tput bold; printf "$system ($realname) ... \n"; tput sgr0;
# Find the Private key to use.
privfile="$(grep IdentityFile $HOME/.ssh/config | grep `echo $system | cut -f 1 -d '-'` | head -n 1 | cut -f 2 -d ' ')"
if [ -z "$privfile" ]; then privfile="$HOME/.ssh/id_rsa"; fi
command='echo mkdir -p "$HOME/.ssh" &> /dev/null; mkdir -p "$HOME/.ssh"; chmod 0700 $HOME $HOME/.ssh; echo "'`cat $privfile.pub`'" > $HOME/.ssh/authorized_keys; cp $HOME/.ssh/authorized_keys $HOME/.ssh/id_rsa.pub; chmod 0600 $HOME/.ssh/authorized_keys; chown -R `whoami` $HOME 2>/dev/null; mv $HOME/.profile $HOME/.profile.bak 2>/dev/null; mv $HOME/.bashrc $HOME/.bashrc.bak 2>/dev/null; printf "";'
# Make sure that we have the right host signature.
ssh-keygen -R "$realname"
if [ $? -ne 0 ]; then printf "FAILED\n\n"; return; fi
ssh-keyscan -H "$realname" >> ~/.ssh/known_hosts
if [ $? -ne 0 ]; then printf "FAILED\n\n"; return; fi
# Set up home folder and send public key.
ssh -t $system bash -c "$command"
if [ $? -ne 0 ]; then printf "FAILED\n\n"; return; fi
# Self-allow key-based auth
scp $privfile $system:.ssh/id_rsa
if [ $? -ne 0 ]; then printf "FAILED\n\n"; return; fi
# Pass profiles.
scp $HOME/.bashrc $system:.bashrc
if [ $? -ne 0 ]; then printf "FAILED\n\n"; return; fi
scp $HOME/.profile $system:.profile
if [ $? -ne 0 ]; then
printf "FAILED\n\n";
else
printf "DONE\n\n"
fi
}
###
### If the search term is in ~/.ssh/config, then replicate to all matching hosts.
### Otherwise, replicate to target specifically.
###
### (Assumed) term to search for as a prefix
if [ `grep -c "$searchterm" "$HOME/.ssh/config"` -gt 0 ]; then
for system in `egrep '^Host ' $HOME/.ssh/config | cut -f 2 -d ' ' | egrep $searchterm`; do
entry=$(cat -n $HOME/.ssh/config | grep $system | head -n 1 | xargs | cut -f 1 -d ' ')
linenum=$(( $entry + 1 ))
realname="$(cat -n $HOME/.ssh/config | grep " ${linenum}$(printf '\t')" | rev | cut -f 1 -d ' ' | rev)"
if [ -z "$realname" ]; then realname="$system"; fi
push;
done
else
system="$searchterm"
push;
fi