## get-ssh-agent
# A pretty simple function intended to convince multiple shell sessions to connect to the same
# ssh-agent instance.

AGENT_FILE_NAME='ssh-agent.env'
# XDG runtime path by default is /run/user/$UID
default_runtime_path="/run/user/$UID"

if [[ "$XDG_RUNTIME_DIR" ]]; then
	ssh_agent_env_file="${XDG_RUNTIME_DIR}/${AGENT_FILE_NAME}"
else
	ssh_agent_env_file="${default_runtime_path}/${AGENT_FILE_NAME}"
fi

function _start_new_ssh_agent () {
	ssh_agent_file=$1
	killall ssh-agent
	# start a new ssh-agent and write its output to the env file.
	ssh-agent | grep -v echo >& "$ssh_agent_file"
	source "$ssh_agent_file"
	echo "New ssh-agent started."
	ssh-add
}

if [[ -e "$ssh_agent_env_file" ]]; then
	# determine if the pid in the env file is still alive
	if [[ -n "$(source "$ssh_agent_env_file"; ps -p "$SSH_AGENT_PID")" ]]; then
		source "$ssh_agent_env_file"
		echo "Existing ssh-agent environment configured with pid ${SSH_AGENT_PID}."
	else
		echo "Existing ssh-agent appears to be dead."
		_start_new_ssh_agent "$ssh_agent_env_file"
	fi
else
	echo "No existing ssh-agent found."
	_start_new_ssh_agent "$ssh_agent_env_file"
fi
