#!/bin/bash
#
# Creates an ssh-agent, writes ssh agent info
# to the file
#
#   /tmp/$(whoami)/.ssh-agent-info-$(hostname)'
#
# and then prompts user for passphrase(s).  Then any shell can use the
# agent by sourcing the info file:
#
#  . /tmp/$(whoami)/ssh-agent-info-$(hostname)
#
# originally by Ted Dustman
#   http://www.cvrti.utah.edu/~dustman/no-more-pw-ssh/

USER=$(whoami)
HOST=$(hostname)
INFO_FILE="/tmp/$USER/.ssh/.ssh-agent-info-$HOST"
PRIVATE_KEY="$HOME/.ssh/id_rsa"

if [ ! -d "/tmp/$USER" ]; then
    echo "making directory /tmp/$USER"
    mkdir "/tmp/$USER" || exit 1
    chmod 700 "/tmp/$USER" || exit 1
fi

if [ ! -d "/tmp/$USER/.ssh" ]; then
    echo "making directory /tmp/$USER/.ssh"
    mkdir "/tmp/$USER/.ssh" || exit 1
    chmod 700 "/tmp/$USER/.ssh" || exit 1
fi

echo "priming agent"
touch "$INFO_FILE" || exit 1
chmod 600 "$INFO_FILE" || exit 1
ssh-agent > "$INFO_FILE" || exit 1
source "$INFO_FILE"
ssh-add "$PRIVATE_KEY" || exit 1
echo "use: . $INFO_FILE"
echo "to enable the agent in your current shell"

exit 0
