#!/bin/sh
set -e

# we hope that these will suit all packages so we don't need overrides
export AUTOMATED_TESTING=1
export NONINTERACTIVE_TESTING=1

TEMP=${ADTTMP:-${TMPDIR:-/tmp}}

TDIR=$(mktemp -d $TEMP/smokeXXXXXX)
file_list=debian/tests/pkg-perl/test-files
if [ ! -r $file_list ]; then
    # backward compatibility for now
    file_list=debian/tests/test-files
fi

if [ -r $file_list ]; then
    egrep -v '^ *(#|$)' $file_list | while read file; do
	[ -r $file ] && cp --parents -a $file $TDIR
    done
else
    [ -d t ] && cp -a t $TDIR
    [ -f test.pl ] && cp -a test.pl $TDIR
fi

skip_list=debian/tests/pkg-perl/skip-smoke
if [ -r $skip_list ]
then
    egrep -v '^ *(#|$)' $skip_list | while read file; do
        rm -f $TDIR/$file
    done
else
    # common nuisances, no value with runtime tests
    rm -f $TDIR/t/pod.t
    rm -f $TDIR/t/pod-coverage.t
    # these should ideally be conditional to RELEASE_TESTING but normally aren't
    # example: libbest-perl_0.15-1
    rm -f $TDIR/t/boilerplate.t
    # example: libhttp-body-perl
    rm -f $TDIR/t/04critic.t
    # example: liborlite-statistics-perl
    rm -f $TDIR/t/97_meta.t
fi

# for Test::Pod
mkdir -p $TDIR/blib

# for 'use blib'
mkdir -p $TDIR/blib/lib $TDIR/blib/arch

# for misc tests that need something in lib or blib/lib/
# cf. libapache-authenhook-perl
mkdir -p $TDIR/lib/Debian/pkgperl
mkdir -p $TDIR/blib/lib/Debian/pkgperl
cat <<'EOF' > $TDIR/lib/Debian/pkgperl/Foobar.pm
package Debian::pkgperl::Foobar;
our $VERSION = '0.01';
1;
__END__
=head1 NAME

Debian::pkgperl::Foobar - dummy module for test checkers

=cut
EOF
cp $TDIR/lib/Debian/pkgperl/Foobar.pm $TDIR/blib/lib/Debian/pkgperl

if [ ! -e $TDIR/MANIFEST ]; then
    cat <<'EOF' > $TDIR/MANIFEST
lib/Debian/pkgperl/Foobar.pm
EOF
fi

if [ ! -e $TDIR/MANIFEST.SKIP ]; then
    cp /dev/null $TDIR/MANIFEST.SKIP
fi

cd $TDIR

if command -v xvfb-run >/dev/null
then
    XVFB="xvfb-run -a"
else
    XVFB=
fi

if [ -d t ]; then test_targets=$(ls -d t/*.t 2>/dev/null || true); fi

if [ ! -n "$test_targets" ]; then
    echo 'Nothing to prove, skipping.'
else
    $XVFB prove --blib --merge --verbose $test_targets
fi

if [ -f test.pl ]; then $XVFB perl ./test.pl; fi

rm -rf $TDIR
