#!/bin/bash
set -e

pkg=maffilter

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

cp -a /usr/share/doc/${pkg}/examples/* "${AUTOPKGTEST_TMP}"

cd "${AUTOPKGTEST_TMP}"

# --- Test 1: Gorilla ---
echo -e "\e[93m\e[1mTest 1\e[0m"
cd Gorilla
maffilter param=MafFilter.bpp

aln="Compara.epo_5_catarrhini_hsap-projected.chr22.subset.nogap.cleaned_aln"
for f in "$aln.dnd" "${aln}_ingroup.dnd" "$aln.statistics.csv" ; do
  test -s "$f" || { echo "MISSING: $f"; exit 1; }
done

# balanced Newick, 4 leaves per statement (Ggor, Hsap, Ptro, Ppyg)
for tree in "$aln.dnd" "${aln}_ingroup.dnd" ; do
  nopen=$(tr -cd '(' < "$tree" | wc -c)
  nclose=$(tr -cd ')' < "$tree" | wc -c)
  [ "$nopen" -eq "$nclose" ] || { echo "unbalanced parens in $tree"; exit 1; }
  grep -q 'Hsap' "$tree" && grep -q 'Ptro' "$tree" \
    && grep -q 'Ggor' "$tree" || { echo "expected labels missing in $tree"; exit 1; }
done

# statistics file has a header and data rows
[ "$(wc -l < "$aln.statistics.csv")" -gt 1 ]
head -n1 "$aln.statistics.csv" | grep -qi "chr"   # adjust to real header field
echo -e "\e[92m\e[1mPassed\e[0m"

# --- Test 2: Ztritici ---
echo -e "\e[93m\e[1mTest 2\e[0m"
cd ../Ztritici
maffilter param=MafFilter.bpp

test -s tba_refIPO323.statistics.csv
test -s Zt12g_CDS.aln

# FASTA sanity: every sequence same length, at least N sequences
awk '/^>/{if(n){print n; exits=1}; n=0; c++; next}{n+=length($0)} END{print n}' Zt12g_CDS.aln \
  | sort -u | wc -l   # should be 1 if all lengths equal; assert accordingly

# CSV has data and no empty rows
[ "$(wc -l < tba_refIPO323.statistics.csv)" -gt 1 ]
! awk -F, 'NF<2' tba_refIPO323.statistics.csv | grep -q .
echo -e "\e[92m\e[1mPassed\e[0m"

echo "All tests passed."
