#!/bin/sh
# autopkgtest check: This runs one specific unit test needing only the goby-io
# jar, and also in order to check the patch about Bzip2 is correct.
# (C) 2021 Pierre Gruet.
# Author: Pierre Gruet <pgt@debian.org>
set -e

pkg=libgoby-java

export LC_ALL=C.UTF-8
if [ "${AUTOPKGTEST_TMP}" = "" ] ; then
  AUTOPKGTEST_TMP=$(mktemp -d /tmp/${pkg}-test.XXXXXX)
  # Double quote below to expand the temporary directory variable now versus
  # later is on purpose.
  # shellcheck disable=SC2064
  trap "rm -rf ${AUTOPKGTEST_TMP}" 0 INT QUIT ABRT PIPE TERM
fi

# We copy the class of the test inside the temp directory.
mkdir -p "${AUTOPKGTEST_TMP}/org/campagnelab/goby/compression/"
cp goby-distribution/src/test/java/org/campagnelab/goby/compression/TestBZip2ChunkCodec.java ${AUTOPKGTEST_TMP}/org/campagnelab/goby/compression/

cd "${AUTOPKGTEST_TMP}"

# Creating the launcher.
cat <<EOF > Test.java
import org.campagnelab.goby.compression.TestBZip2ChunkCodec;
import java.io.IOException;

public class Test {
    public static void main(String[] args) {
        try {
            TestBZip2ChunkCodec t = new TestBZip2ChunkCodec();
            t.roundTrip();
        } catch (IOException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
EOF

# Removing the junit stuff in the class of the test.
sed -i 's/^import org\.junit\.Test;$//' org/campagnelab/goby/compression/TestBZip2ChunkCodec.java
sed -i 's/^import static junit\.framework\.Assert\.assertNotNull;$//' org/campagnelab/goby/compression/TestBZip2ChunkCodec.java
sed -i 's/@Test//' org/campagnelab/goby/compression/TestBZip2ChunkCodec.java
sed -i 's/assertNotNull(decoded);/if (decoded == null) { System.exit(1); }/' org/campagnelab/goby/compression/TestBZip2ChunkCodec.java

# Building and running.
javac -cp .:/usr/share/java/goby-io.jar:/usr/share/java/protobuf.jar Test.java org/campagnelab/goby/compression/TestBZip2ChunkCodec.java
java -cp .:/usr/share/java/goby-io.jar:/usr/share/java/protobuf.jar Test

if [ $? -eq 0 ]; then
  echo "Test ran successfully"
else
  echo "Test failed to run"
  exit 1
fi
