#!/bin/bash
# This must be called as (note the trailing dot):
#
#    stunnel-rsync HOSTNAME rsync --server --daemon .
#
# ... which is typically done via the rsync-ssl script, which results in something like this:
#
#    rsync --rsh=stunnel-rsync -aiv HOSTNAME::module [ARGS]
#
# This SSL setup based on the files by:  http://dozzie.jarowit.net/trac/wiki/RsyncSSL
# Note that this requires at least version 4.x of stunnel.

# The current environment can override using the RSYNC_SSL_* values:
if [ x"$RSYNC_SSL_CERT" = x ]; then
    cert=""
else
    cert="cert = $RSYNC_SSL_CERT"
fi
if [ x"$RSYNC_SSL_CA_CERT" ]; then
    cafile=""
    verify=0
else
    cafile="CAfile = $RSYNC_SSL_CA_CERT"
    verify=3
fi
port=${RSYNC_SSL_PORT:-874}

# If the user specified USER@HOSTNAME::module, then rsync passes us
# the -l USER option too, so we must be prepared to ignore it.
if [ x"$1" = x"-l" ]; then
    shift 2
fi

hostname=$1
shift

if [ x"$hostname" = x -o x"$1" != x"rsync" -o x"$2" != x"--server" -o x"$3" != x"--daemon" ]; then
    echo "Usage: stunnel-rsync HOSTNAME rsync --server --daemon ." 1>&2
    exit 1
fi

# devzero@web.de came up with this no-tmpfile calling syntax:
@stunnel4@ -fd 10 11<&0 <<EOF 10<&0 0<&11 11<&-
foreground = yes
debug = crit
connect = $hostname:$port
client = yes
TIMEOUTclose = 0
verify = $verify
$cert
$cafile
EOF
