#!/bin/sh

set -eu

# When not under autopkgtest, test against the source directory
if [ -z "${AUTOPKGTEST_TMP:-}" ]; then
  base=$(readlink -f $(dirname $0)/../..)
  export PATH=${base}/debian/tests/bin:${PATH}
  export RUBYLIB=${base}/lib
  unset base
fi

# prepare test dir
tmp_dir=$(mktemp -d)
trap cleanup INT TERM EXIT
cleanup() {
  if [ -z "${DEBUG:-}" ]; then
    rm -rf "${tmp_dir}"
  else
    echo
    echo "I: temporary directory left at ${tmp_dir}"
  fi
}


source_test_dir=$(dirname $0)/../../t
test_dir=${tmp_dir}/tests
cp -r ${source_test_dir} ${test_dir}
mkdir -p $test_dir

# remove unwanted tests
for t in $(sed -e '/^\s*#/d' $(dirname $0)/exclude); do
  rm -f ${test_dir}/$t
done

# prepare to run
cd ${test_dir}
prog=$(basename $0)
if [ ${prog} != "test" ]; then
  export model=${prog##test-}
fi
export RUBY_ENGINE=ruby
dd if=/dev/urandom bs=1M count=30 of=random_blob
mkdir -p trash

if [ $# -eq 0 ]; then
  set -- t[0-9][0-9][0-9][0-9]-*
fi

# run!
failed=""
rc=0
for script in "$@"; do
  echo "===> ${script} <==="
  if ! sh ${script} --verbose; then
    echo "===> FAILED: ${script}"
    failed="${failed} ${script}"
    rc=1
  fi
  echo
done
if [ -n "${failed}" ]; then
  echo "Failed: ${failed}"
fi
test $rc -eq 0
