## 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 () {
	killall ssh-agent
	# start a new ssh-agent and write its output to the env file.
	ssh-agent | grep -v echo >&"$ssh_agent_env_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 [[ "$(source "$ssh_agent_env_file"; ps -ef | grep "$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
	fi
else
	echo "No existing ssh-agent found."
	_start_new_ssh_agent
fi
