--- pinentry-emacs.orig	2017-11-27 09:56:54 UTC
+++ pinentry-emacs
@@ -1,4 +1,4 @@
-#!/bin/bash
+#!/usr/local/bin/bash
 set -o pipefail
 echo OK
 while read cmd rest
@@ -28,10 +28,19 @@ do
         ;;
         GETPIN)
 
-            RES=$(emacsclient -e "(pinentry-emacs \"$DESC\" \"$PROMPT\" \"$OK\" \"$ERROR\")" | sed -e 's/^"//' -e 's/"$//')
+            # Resolve the Emacs server socket the way emacsclient does
+            # ($EMACS_SOCKET_NAME, then $XDG_RUNTIME_DIR/emacs/server), but
+            # fall back to $HOME/.run/emacs/server when gpg-agent was started
+            # with a different XDG_RUNTIME_DIR than the Emacs daemon.
+            SOCKET="${EMACS_SOCKET_NAME:-${XDG_RUNTIME_DIR:+$XDG_RUNTIME_DIR/emacs/server}}"
+            if [ -n "$SOCKET" ] && [ ! -S "$SOCKET" ] && [ -S "$HOME/.run/emacs/server" ]; then
+                SOCKET="$HOME/.run/emacs/server"
+            fi
+            RES=$(emacsclient ${SOCKET:+--socket-name="$SOCKET"} -e "(pinentry-emacs \"$DESC\" \"$PROMPT\" \"$OK\" \"$ERROR\")" | sed -e 's/^"//' -e 's/"$//')
             if [ $? -ne 0 ]
             then
-                RES=$(lukspinentry)
+                echo ERR 83886179 Operation cancelled
+                exit 1
             fi
             echo D $RES
             echo OK
