#!/bin/bash

set -e

# Build mosh.  We need to do this because some of the test programs
# expect to link against libraries built here.
#
# We could use "Restrictions: build-needed" on d/t/control, but that'd
# also invoke dh_auto_test which only wastes our time.

echo "I: Copying source tree so that we can modify it"
mkdir "$AUTOPKGTEST_TMP/build"
shopt -s nullglob
cp -a * "$AUTOPKGTEST_TMP/build"
cd "$AUTOPKGTEST_TMP/build"

echo "I: Building mosh"
./debian/rules override_dh_auto_configure
make -j$(nproc)

# Remove all possible local mosh binaries that could confuse the test
# suite.
echo "I: Removing all locally-built mosh binaries"
rm -fv \
   scripts/mosh \
   src/frontend/mosh-client \
   src/frontend/mosh-server \
   src/tests/mosh-client \
   src/tests/mosh-server

# Adjust mosh's test scripts to use mosh-{client,server} from the
# system.
echo "I: Adjusting mosh's test suite to use the system-installed mosh binaries"
find src/tests/ -type f -print0 | xargs -0 sed -i \
    -e 's@ --client=.\?[^ ]*\/mosh-client.\? @ --client=/usr/bin/mosh-client @' \
    -e 's@ --server=.\?[^ ]*\/mosh-server.\? @ --server=/usr/bin/mosh-server @' \
    -e 's@\.\.\/\.\.\/scripts\/mosh@/usr/bin/mosh@' \
    -e 's@export MOSH_CLIENT=.*@export MOSH_CLIENT="/usr/bin/mosh-client"@' \
    -e 's@export MOSH_SERVER=.*@export MOSH_SERVER="/usr/bin/mosh-server"@'

echo "I: Running tests"
if ! make check; then
    echo "E: Testsuite failed to run:"
    if [ -f src/tests/test-suite.log ]; then
	echo
	cat src/tests/test-suite.log
    fi
    exit 1
fi

exit 0
