#!/bin/bash

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

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=$!

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

($SSH $SERVERNAME $REMOTESMDCLIENT $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: /' \
		| $SED "s/@@INVERSECOMMAND@@/smd-pull/" \
		| $SED "s/@@ENDPOINT@@/$REPNAME/"
	grep ^ERROR $SL \
		| $SED 's/^/smd-client: /' \
		| $SED "s/@@INVERSECOMMAND@@/smd-pull/" \
		| $SED "s/@@ENDPOINT@@/$REPNAME/"
	grep ^ssh: $SL \
		| $SED 's/^/smd-client: ERROR: /'
fi
if [ $SHOWTAGS = 1 ]; then
	echo "`date`: smd-push $SERVERNAME" >> $SL
	grep ^TAGS $CL \
		| $SED "s/^/$REPNAME: smd-server@localhost: /" \
		| $SED "s/@@INVERSECOMMAND@@/smd-pull/" \
		| $SED "s/@@ENDPOINT@@/$REPNAME/"
	grep ^TAGS $SL \
		| $SED "s/^/$REPNAME: smd-client@$SERVERNAME: /" \
		| $SED "s/@@INVERSECOMMAND@@/smd-pull/" \
		| $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-client@$SERVERNAME: TAGS: error::context(ssh) probable-cause(network) human-intervention(avoidable) suggested-actions(retry)"
	fi

fi

exit $EXITCODE
