#! /bin/sh
set -e

pkg=pyfastx
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}"
cp -a /usr/share/doc/${pkg}/examples/* .
# Keep some compressed files for later, as they are expected to remain so.
cp test.fa.gz test.fa.gz.keep
cp test.fq.gz test.fq.gz.keep
gunzip *.gz
mv test.fa.gz.keep test.fa.gz
mv test.fq.gz.keep test.fq.gz

# Note: reference results were obtained by running the command manually during
# the initial packaging.  They may need to be adjusted if the command output
# were to change for, say, cosmetic reasons.

echo '$ pyfastx --help'
pyfastx --help

readonly PYFASTX_COMMANDS="$(
	pyfastx --help \
	| sed -n 's/^    \([^ ]\+\)  .*$/\1/p' \
	| xargs
)"
echo "\$ # Found pyfastx commands: '$PYFASTX_COMMANDS'"

for PYFASTX_COMMAND in ${PYFASTX_COMMANDS}
do
	echo "\$ pyfastx $PYFASTX_COMMAND --help"
	pyfastx "$PYFASTX_COMMAND" --help
done

echo '$ pyfastx --version'
pyfastx --version

# Try indexing everything.
for FASTX in *.fa *.fq *.fa.gz *.fq.gz
do
	echo '$ pyfastx index '"$FASTX"
	pyfastx index "$FASTX"
	test -s "${FASTX}.fxi"
done

echo '$ pyfastx stat protein.fa'
pyfastx stat protein.fa
# Compare output, if that makes sense.
pyfastx stat protein.fa > result
cat > expected << END
fileName  	seqType	seqCounts	totalBases	GC%	 avgLen	medianLen	maxLen	minLen	N50	L50
protein.fa	protein	       17	      2265	  -	133.235	     80.0	   419	    23	263	  4
END
diff -Naur expected result

echo '$ pyfastx split -n 2 protein.fa'
pyfastx split -n 2 protein.fa
test -s protein.1.fa
test -s protein.2.fa

echo '$ pyfastx fq2fa test.fq -o test.fa'
pyfastx fq2fa test.fq -o test.fa
test -s test.fa

# Get the four first characters of the first region.
echo '$ pyfastx subseq protein.fa UPI0000000011:1-4'
pyfastx subseq protein.fa UPI0000000011:1-4
# Compare results if that makes sense.
pyfastx subseq protein.fa UPI0000000011:1-4 -o result
cat > expected << END
>UPI0000000011:1-4
MVDA
END
diff -Naur expected result

# Sampling is random, don't try to check output too finely.
echo '$ pyfastx sample -n 1 test.fq.gz -o sample.fq'
pyfastx sample -n 1 test.fq.gz -o sample.fq
test -s sample.fq

# Get the first region.
echo '$ pyfastx extract protein.fa UPI0000000011'
pyfastx extract protein.fa UPI0000000011
# Compare results, if that makes sense.
pyfastx extract protein.fa UPI0000000011 -o result
cat > expected << END
>UPI0000000011 status=active
MVDAITVLTAIGITVLMLLMVISGAAMIVKELNPNDIFTMQSLKFNRAVTIFKYIGLFIY
IPGTIILYATYVKSLLMKS
END
diff -Naur expected result
