#!/bin/sh
# This is the build script invoked for running autotools based builds. We use
# autotools at least for measurement-kit/measurement-kit.
set -ex
REPOROOT=$(cd $(dirname $0)/../../../ && pwd -P)
cd $REPOROOT
env|grep -v TOKEN|sort

./autogen.sh
# Enforce -Werror when building on Travis to make sure warnings are
# not going to be neglected and instead block automatic builds.
export CXXFLAGS="$CXXFLAGS -Werror"
export CFLAGS="$CFLAGS -Werror"
./configure --disable-dependency-tracking $CONFIGURE_OPTIONS
make -j`nproc` $MAKE_OPTIONS

#
# The following (adapted from the docker-run script) is such that we
# modify upload traffic to look like a cable modem.
#
tc qdisc add dev eth0 root handle 1: htb default 12
tc class add dev eth0 parent 1:1 classid 1:12 htb rate 5mbit ceil 5mbit
tc qdisc add dev eth0 parent 1:12 netem delay 14ms

# Run an explicit nettest to visually confirm that the performance we're
# getting is in line with what we would expect.
./measurement_kit ndt

# Setting empty TESTS so later we can run tests with higher parallelism
make check -j`nproc` TESTS= $MAKE_CHECK_OPTIONS
make check -j6 $MAKE_CHECK_OPTIONS || {
  if [ -f ./test-suite.log ]; then
    cat ./test-suite.log
  fi
  echo "* Some tests failed; attempting to re-run them"
  make recheck -j6 $MAKE_CHECK_OPTIONS || {
    if [ -f ./test-suite.log ]; then
      cat ./test-suite.log
    fi
    echo "* Some tests failed; attempting to re-run them one more time"
    make recheck -j6 $MAKE_CHECK_OPTIONS || {
      if [ -f ./test-suite.log ]; then
        cat ./test-suite.log
      fi
      exit 1
    }
  }
}

if [ "$BUILD_TYPE" = "coverage" ]; then
  lcov --directory . --capture -o lcov-all.info
  lcov --remove lcov-all.info                                                  \
    '/mk/include/private/*' '/mk/include/measurement_kit/internal/vendor/*'    \
    '/mk/example/*' '/mk/src/measurement_kit/*'                                \
    -o lcov.info
  curl -fsSL -o codecov.sh https://codecov.io/bash
  bash codecov.sh -X gcov -f lcov.info
fi

make install
