#!/bin/bash

# the idea is (where == is a bi-directional pipe) :
#
#   ssh foo smd-client == tee log == smd-server
#

set -e
#set -x
cd

PREFIX="@PREFIX@"
if [ `echo $PREFIX | cut -c -1` = "@" ]; then
	SMDROOT=~/Projects/syncmaildir
	echo "smd-push not installed, assuming smd-common is in $SMDROOT"
else
	SMDROOT=$PREFIX/share/syncmaildir
fi

. $SMDROOT/smd-common

($MITM $CtS > $LtS) < $CtL &
LOGGER1=$!

($MITM $StC > $LtC) < $StL &
LOGGER2=$!

($SMDSERVER $VERBOSE $CLIENTNAME $MAILBOX < $LtC 2> $CL) > $CtL &
CLIENT=$!

($SSH $SERVERNAME $SMDCLIENT $VERBOSE $CLIENTNAME $MAILBOX < $LtS 2> $SL) > $StL &
SERVER=$!

EXITCODE=0
wait $SERVER || EXITCODE=1
wait $CLIENT || EXITCODE=1 

if [ $EXITCODE = 1 ]; then
	grep ^ERROR $CL | sed 's/^/smd-server: /'
	grep ^ERROR $SL | sed 's/^/smd-client: /'
fi

exit $EXITCODE
