Using gpg-agent for GPG and SSH

This is my (melmothX's) setup for gpg-agent

 apt-get install gnupg-agent

Check if ssh-agent is running, locate where is started (in .xinitrc if you don't use any *dm), kill it and disabled it.

I don't want to mess with the agent too much, and I also want to survive between X restarting. So this is the relevant part of my ~/.xinitrc

# define a start gpg agent function
startgpgagent () {
    # check if it's running. if it is, complains and don't start it again
    if ps -u $(whoami) | grep -q gpg-agent; then
    echo "gpg-agent is running! wtf??"
    else
    gpg-agent --daemon --enable-ssh-support \
        --write-env-file "${HOME}/.gpg-agent-info" \
        --log-file "${HOME}/.my-gpg-agent.log"
    fi
}

if [ -f "${HOME}/.gpg-agent-info" ]; then
    . "${HOME}/.gpg-agent-info"
    # is it running? if not, start it 
    if ! ps -u $(whoami) | grep -q -e "$SSH_AGENT_PID.*gpg-agent"; then
    echo "starting gpg-agent"
    rm "${HOME}/.gpg-agent-info"
    startgpgagent
    fi
else
    startgpgagent
fi

# export the variables
. "${HOME}/.gpg-agent-info"
export GPG_AGENT_INFO
export SSH_AUTH_SOCK
export SSH_AGENT_PID


if ! ps -u $(whoami) | grep -q emacs ; then 
    echo "starting emacs"
    emacs --daemon
    else 
    echo "emacs already running"
fi

# emacs is supposed to survive the X sessions, so try to update the variables
emacsclient -e "(setenv \"GPG_AGENT_INFO\" \"$GPG_AGENT_INFO\")"
emacsclient -e "(setenv \"SSH_AUTH_SOCK\" \"$SSH_AUTH_SOCK\")"
emacsclient -e "(setenv \"SSH_AGENT_PID\" \"$SSH_AGENT_PID\")"
exec openbox-session

Then in ~/.bashrc we add this section:

### GPG agent config

if [ -f "${HOME}/.gpg-agent-info" ]; then
    . "${HOME}/.gpg-agent-info"
    export GPG_AGENT_INFO
    export SSH_AUTH_SOCK
    export SSH_AGENT_PID
fi
# this avoid the passwd being asked on the console while in X
echo UPDATESTARTUPTTY | gpg-connect-agent 2>/dev/null > /dev/null
GPG_TTY=$(tty)
export GPG_TTY

### end

That's it.

Important: the first time you run ssh-add you will be queried to provide a passphrase to store the ssh-key. It's different from the SSH passphrase and it has the purpose to safely store the secret key in ~/.gnupg/private-keys-v1.d

NOTE: If you followed the old tutorial, please remove or neutralize ~/.bash_logout Now the daemon is killed only at the shutdown by the OS, not when logging out.