#!/bin/sh

set -e

if [ "$1" = "-j" ] ; then
    NUMJOBS="$2"
    test "$NUMJOBS" -gt 0 || (
        echo "$NUMJOBS is not an integer greater than 0" >&2 && exit 1)
    PARALLEL_ARGS="-j $NUMJOBS"
    shift
    shift
fi

NEW_SUITE=1

if [ "$1" = "-t" ] ; then
    TAG=yes
elif [ "$1" = "--legacy-only" ] ; then
    NEW_SUITE=0
    shift
fi

LC_ALL="C"
LINTIAN_ROOT=""
LINTIAN_PROFILE=debian
LINTIAN_INTERNAL_TESTSUITE=1
NO_PKG_MANGLE=true
unset MAKEFLAGS
# Ensure Lintian works without $ENV{HOME}
unset HOME

[ "$TEST_WORK_DIR" ] || TEST_WORK_DIR="debian/test-out"

export LC_ALL
export LINTIAN_ROOT
export LINTIAN_PROFILE
export LINTIAN_INTERNAL_TESTSUITE
export NO_PKG_MANGLE

fail(){
    echo "$1" >&2
    exit 1
}

# In Wheezy (and newer) libc-bin provides a C.UTF-8 locale.
# In Squeeze (and older) we either need locales-all or generate
# an en_US.UTF-8 locale ourselves.
if [ -e "/usr/lib/locale/C.UTF-8" ] ; then
    echo "Using C.UTF-8 locale from /usr/lib/locale"
    unset LOCPATH
elif dpkg -l | grep -q ^"ii *locales-all " ; then
    echo "Using en_US.UTF-8 locale from locales-all"
    unset LOCPATH
else
    LOCPATH="$(pwd)/debian/test.locale"
    export LOCPATH

    # Apparently, it is not possible to generate a C.UTF-8 locale in
    # Squeeze, so settle with an en_US.UTF-8 one.
    if [ ! -e "$LOCPATH"/en_US.UTF-8 ] ; then
        echo "Generating en_US.UTF-8 locale for the test suite"
        mkdir -p "$LOCPATH"
        localedef -i en_US -c -f UTF-8 -A /usr/share/locale/locale.alias \
            --quiet "$LOCPATH"/en_US.UTF-8 || fail "Locale generation failed"
    else
        echo "Using pre-generated en_US.UTF-8 locale in $LOCPATH"
    fi
fi

if [ "${NEW_SUITE}" = 1 ] ; then
    t/runtests --dump-logs -k $PARALLEL_ARGS t "$TEST_WORK_DIR" "$@"
fi
if [ "$TAG" = "" ] ; then
    echo " --- LEGACY TEST SUITE ---"
    testset/runtests -k testset "$TEST_WORK_DIR" "$@"
fi

# Local Variables:
# indent-tabs-mode: nil
# End:
# vim: syntax=sh sw=4 sts=4 sr et
