#!/bin/bash

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

set -e
#set -x

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

. $SMDROOT/smd-common

# we move to the home, since Mail paths are relative
# to the home
cd

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

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

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

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

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

if [ $EXITCODE = 1 ]; then
	grep ^ERROR $SL \
		| $SED 's/^/smd-server: /' \
		| $SED "s/@@INVERSECOMMAND@@/smd-push/" \
		| $SED "s/@@ENDPOINT@@/$REPNAME/"
	grep ^ERROR $CL \
		| $SED 's/^/smd-client: /' \
		| $SED "s/@@INVERSECOMMAND@@/smd-push/" \
		| $SED "s/@@ENDPOINT@@/$REPNAME/"
	grep ^ssh: $SL \
		| $SED 's/^/smd-server: ERROR: /'
fi
if [ $SHOWTAGS = 1 ]; then
	echo "`date`: smd-pull $SERVERNAME" >> $CL
	grep ^TAGS $SL \
		| $SED "s/^/$REPNAME: smd-server@$SERVERNAME: /" \
		| $SED "s/@@INVERSECOMMAND@@/smd-push/" \
		| $SED "s/@@ENDPOINT@@/$REPNAME/"
	grep ^TAGS $CL \
		| $SED "s/^/$REPNAME: smd-client@localhost: /" \
		| $SED "s/@@INVERSECOMMAND@@/smd-push/" \
		| $SED "s/@@ENDPOINT@@/$REPNAME/"
	if [ `grep ^TAGS $SL|wc -l` = 0 ] && \
	   [ `grep ^TAGS $CL|wc -l` = 0 ]; then
		# it may be that ssh failed to resolve the hostname
		# so we generate a fake tag for it
		cat $SL $CL
		echo "$REPNAME: smd-server@$SERVERNAME: TAGS: error::context(ssh) probable-cause(network) human-intervention(avoidable) suggested-actions(retry)"
	fi
fi

exit $EXITCODE
