#!/bin/bash

# Run notmuch on remote host over SSH
#
# https://notmuchmail.org/remoteusage/
#
# Put this script in your path and add (setq notmuch-command
# "notmuch-remote") to your emacs configuration.
#
# Add a host specification for "notmuch" to ~/.ssh/config to set the
# remote host and (optionally) remote user.
#
# Host notmuch
#     HostName host.example.org
#     User username

SSH_REMOTE_HOST=notmuch

# Note: for security reasons the control socket is placed in ~/.ssh
SSH_CONTROL_PATH='-o ControlPath=~/.ssh/notmuch-remote.%r@%h:%p'

# Start a background master connection if one isn't running yet
ssh ${SSH_CONTROL_PATH} -O check ${SSH_REMOTE_HOST} 2>/dev/null ||
ssh ${SSH_CONTROL_PATH} -MNf ${SSH_REMOTE_HOST}

# The ControlPersist option (in OpenSSH 5.6) could be used to start
# the master connection automatically when "ssh host notmuch" is run.

# This requires the bash version of printf (bashism)
printf -v ARGS "%q " "$@"
exec ssh ${SSH_CONTROL_PATH} ${SSH_REMOTE_HOST} notmuch ${ARGS}