-##Write a simple wrapper shell script##
-Now we will need to write a simple shell script that replaces the
-call to the notmuch binary with a call to notmuch over ssh.
-
-Note that this shell script also pauses briefly after every ten search
-entries. This is currently necessary so that the emacs process-filter
-doesn't chop off messages. It's an obvious hack, and hopefully won't
-be necessary in the furture.
-
- #!/usr/bin/env bash
-
- SSH_BIN="/path/to/ssh/on/client"
- USER="user_name"
- HOST="server_name"
- NOTMUCH_REMOTE_BIN="/path/to/notmuch/on/server"
-
- if [ $1 = "search" ]; then
- COUNT=0;
- OUT=`$SSH_BIN $USER@$HOST $NOTMUCH_REMOTE_BIN $@`
- echo "$OUT" | while read line; do
- COUNT=`expr $COUNT + 1`
- echo "$line";
- if [ $COUNT = 10 ]; then
- sleep 0.1;
- fi
- done
- else
- $SSH_BIN $USER@$HOST $NOTMUCH_REMOTE_BIN $@
- fi
-
+
+##Write a wrapper shell script##
+
+Now we will need to write a simple shell script that does two things:
+
+1. replaces the call to the notmuch binary with a call to notmuch
+over ssh.
+
+2. sets up a running, detached, ssh connection to the server, so that
+future calls can reuse the socket.
+
+ #!/usr/bin/env bash
+
+ SSH_BIN="ssh"
+ USER="example_user"
+ SSH_HOST="example.com"
+ SOCKET_DIR="/tmp/notmuch_socks"
+ SSH_SOCKET="${SOCKET_DIR}/ssh.socket"
+ NOTMUCH_REMOTE_BIN="notmuch"
+ DTACH="/usr/bin/dtach"
+ DTACH_SOCKET="${SOCKET_DIR}/dtach.socket"
+
+ check_for_socket_dir ()
+ {
+ [ -d "${SOCKET_DIR}" ]
+ }
+
+ check_socket_dir_owner_and_perm ()
+ {
+ [ "$(stat -c %U ${SOCKET_DIR})" = "$(whoami)" ] &&
+ [ "$(stat -c %a ${SOCKET_DIR})" = "700" ]
+ }
+
+ create_socket_dir ()
+ {
+ mkdir "${SOCKET_DIR}" $(id -u)
+ chmod 700 "${SOCKET_DIR}"
+ }
+
+ check_create_socket_dir ()
+ {
+ if ! check_for_socket_dir; then
+ create_socket_dir ||
+ (echo "Couldn't create socket directory at ${SOCKET_DIR}" >&2 && exit 1)
+ elif ! check_socket_dir_owner_and_perm; then
+ (echo "Incorrect permissions at ${SOCKET_DIR}" >&2 && exit 1)
+ fi
+ }
+
+ check_for_socket ()
+ {
+ [ -S "${SSH_SOCKET}" ]
+ }
+
+ start_socket ()
+ {
+ dtach_command="${DTACH} -n ${DTACH_SOCKET} ${SSH_BIN} -M -S ${SSH_SOCKET} ${USER}@${SSH_HOST}"
+ command -v ${DTACH} &>/dev/null && ${dtach_command} ||
+ echo "${DTACH} not installed"
+ }
+
+ notmuch_run ()
+ {
+ check_for_socket || (check_create_socket_dir && start_socket)
+ CMD=$1
+ shift
+ printf -v ARGS "%q " "$@"
+ $SSH_BIN -S $SSH_SOCKET $USER@$SSH_HOST $NOTMUCH_REMOTE_BIN ${CMD} ${ARGS}
+ }
+
+ notmuch_run $@
+
+