#!/bin/sh

#
# Harness script for Mosh tests, server side.  Runs test script and
# then captures screen with `tmux capture-pane`.  Captures exitstatus
# of both and returns appropriate errors.
#

# If MOSH_E2E_WAIT is set, then the test will wait for another tmux
# client to attach to the test session before starting, and will wait
# for other tmux clients to detach before exiting.
wait_for_clients()
{
    if [ -z "$MOSH_E2E_WAIT" ]; then
	return
    fi
    expected=$1
    while true; do 
	n=$(tmux list-clients -F . | wc -l)
	if [ $expected -eq 1 ]; then
	    if [ $n -eq 1 ]; then
		return
	    fi
	elif [ $n -ne 1 ]; then
	    return
	fi
	sleep 1
    done
}

export MOSH_SERVER_PID=$PPID

if [ $# -lt 2 ]; then
    printf "not enough args\n" >&2
    exit 99
fi
testname=$1
shift
rm -f "$testname.capture" "$testname.exitstatus"
trap ":" TERM HUP QUIT # If the session closes on us, let the test we're running drive.
on_exit() {
    rv=$?
    echo $rv > "$testname.exitstatus"
    exit $rv
}
trap on_exit EXIT
# check for tmux
if [ -z "$TMUX_PANE" ]; then
    printf "not running under tmux\n" >&2
    exit 99
fi
wait_for_clients 2
# run harnessed command
eval "$@"
testret=$?
# Capture mosh-server runtime if possible.
runtime=$(ps -o time= $PPID 2>/dev/null)
if [ $? -ne 0 ]; then # Cygwin...
    runtime=-
fi
# Wait for tmux client screen to become up to date.
sleep 1
printf "@@@ server complete @@@" >&2
wait_for_clients 1
i=0
while [ $i -lt 60 ]; do
    if grep -q "@@@ server complete @@@" "$testname.tmux.log"; then
	break
    fi
    i=$((i+1))
    sleep 1
done
if [ $i -ge 60 ]; then
    printf "wait for tmux client update failed, erroring test\n" >&2
    exit 99
fi
# capture screen
if ! tmux capture-pane -et "$TMUX_PANE"; then
    printf "tmux capture-pane failed, erroring test\n" >&2
    exit 99
fi
if ! tmux save-buffer "$testname.capture"; then
    printf "tmux save-buffer failed, erroring test\n" >&2
    exit 99
fi
# Dump runtime into tmux log.
printf "@@@ runtime %s @@@\n" "$runtime"
# return useful exitstatus from harnessed command
if [ $testret -ne 0 ]; then
    exit 1
fi
exit 0
