#!/bin/bash
set -e

pkg=nanook

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

cd "${AUTOPKGTEST_TMP}"

tar xf /usr/share/doc/${pkg}/examples/data.tar.gz

cd data/nanook_ecoli_500/references
lastdb -Q 0 ecoli_dh10b_cs ecoli_dh10b_cs.fasta
cd ..

nanook extract -s N79596_dh10b_8kb_11022015
nanook align -s N79596_dh10b_8kb_11022015 -r references/ecoli_dh10b_cs.fasta
nanook analyse -s N79596_dh10b_8kb_11022015 -r references/ecoli_dh10b_cs.fasta -passonly

cd ../..
SAMPLE=data/nanook_ecoli_500/N79596_dh10b_8kb_11022015

# Reads must have been extracted for each strand type.
for type in Template Complement 2D; do
  readfile=$(ls "${SAMPLE}/fasta/pass/${type}"/*.fasta)
  [ -s "${readfile}" ] || { echo "FAIL: no reads extracted for ${type}"; exit 1; }
  [ "$(grep -c '^>' "${readfile}")" -ge 1 ] || { echo "FAIL: empty ${type} read file"; exit 1; }
done

# Alignments must be non-empty for each strand type.  An empty MAF here
# means lastal failed (e.g. incompatible parameters), which previously
# broke the whole pipeline.
for type in Template Complement 2D; do
  maffile=$(ls "${SAMPLE}/last/pass/${type}"/*.maf)
  [ -s "${maffile}" ] || { echo "FAIL: no alignments produced for ${type}"; exit 1; }
  [ "$(grep -c '^a score' "${maffile}")" -ge 1 ] || { echo "FAIL: no alignment records in ${type} MAF"; exit 1; }
done

# Analysis must have produced its summary files.
[ -s "${SAMPLE}/analysis_last_passonly/all_summary.txt" ] || { echo "FAIL: no summary from analyse"; exit 1; }
for type in Template Complement 2D; do
  [ -s "${SAMPLE}/analysis_last_passonly/all_${type}_alignment_summary.txt" ] || \
    { echo "FAIL: missing ${type} alignment summary"; exit 1; }
done
