#!/bin/bash
set -ex

pkg=canu

export LC_ALL=C.UTF-8
if [ "${AUTOPKGTEST_TMP}" = "" ] ; then
  AUTOPKGTEST_TMP=$(mktemp -d /tmp/${pkg}-test.XXXXXX)
  # shellcheck disable=SC2064
  trap "rm -rf ${AUTOPKGTEST_TMP}" 0 INT QUIT ABRT PIPE TERM
fi
export TMPDIR="${AUTOPKGTEST_TMP}"

#if [ "${AUTOPKGTEST_ARTIFACTS}" = "" ] ; then
#  AUTOPKGTEST_ARTIFACTS=${PWD}
#fi
#cd "${AUTOPKGTEST_ARTIFACTS}"
# Too big, see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=1050388
cd "${AUTOPKGTEST_TMP}"

cores=$(nproc)
mem=$(free --giga | grep Mem | awk '{ print $7}')
if ((mem < 6)) ; then
	echo "At least 6G of memory is required to run this test."
	exit 77
elif ((mem < 8)) ; then
	oeaMemory=oeaMemory=${mem}g
	redMemory=redMemory=${mem}g
else
	oeaMemory=
	redMemory=
fi
if ((cores < 4)) ; then
	corThreads=corThreads=${cores}
else
	corThreads=
fi

curl -L -o "${AUTOPKGTEST_TMP}"/pacbio.fastq \
	http://gembox.cbcb.umd.edu/mhap/raw/ecoli_p6_25x.filtered.fastq
set +e
# shellcheck disable=SC2086
canu -p ecoli -d ecoli-pacbio \
	genomeSize=4.8m \
	maxThreads="${cores}" ${corThreads} ${oeaMemory} ${redMemory} \
	-pacbio "${AUTOPKGTEST_TMP}"/pacbio.fastq ; result=$?

if [ ! "${AUTOPKGTEST_ARTIFACTS}" = "" ] ; then
	cp ecoli-pacbio/*.report ecoli-pacbio/*.err "${AUTOPKGTEST_ARTIFACTS}/"
	cp $(find ecoli-pacbio -name "*\.out") "${AUTOPKGTEST_ARTIFACTS}/"
	cp -r ecoli-pacbio/canu-logs "${AUTOPKGTEST_ARTIFACTS}/"
fi

exit ${result}
