#!/bin/bash

# Check to see if we at least have an agent running, and have previously
# saved exports.
if [ ! `pgrep -n ssh-agent` ] || [ ! -f ~/temp/ssh-agent-exports.sh ]
then
    # If not, create a new agent and save the details.
    echo $(ssh-agent) > ~/temp/ssh-agent-exports.sh
    chmod +x ~/temp/ssh-agent-exports.sh

# If we do have previous details and a running agent, make sure that 
# the details match an available agent (and not one that was killed).
elif [[ `(source ~/temp/ssh-agent-exports.sh; ssh-add -l 2>&1)` =~ "Could not open" ]]
then
    # If the current details are for a dead agent, create a new agent and
    # save the details.
    echo $(ssh-agent) > ~/temp/ssh-agent-exports.sh
    chmod +x ~/temp/ssh-agent-exports.sh
fi

# Finally, if we were called without an argument, echo the current settings.
if [ "$1" = "" ]
then
    cat ~/temp/ssh-agent-exports.sh
# If we do have an argument then evaluate that argument in a new shell which
# has the SSH agent defined.
else
    (
    source ~/temp/ssh-agent-exports.sh
    eval $1
    )
fi
