#!/bin/bash
set -e

pkg=cufflinks

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

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

cd "${AUTOPKGTEST_TMP}"

## start with simnple smoke test

# Every binary shipped by the cufflinks package must be installed
for bin in cufflinks cuffcompare cuffdiff cuffmerge cuffnorm cuffquant \
           gtf_to_sam compress_gtf; do
    command -v "$bin" >/dev/null 2>&1 || {
        echo "ERROR: $bin not found in PATH"
        exit 1
    }
done

# Running cufflinks without arguments prints a version banner to stderr
# (and exits non-zero).  Verify the binary starts and links correctly.
banner=$(cufflinks 2>&1 >/dev/null || true)
printf '%s\n' "$banner" | grep -q "cufflinks v" || {
    echo "ERROR: no version banner from cufflinks"
    echo "--- output was ---"
    printf '%s\n' "$banner"
    exit 1
}

# Run functional test 

# 1) cufflinks: assemble transcripts from the alignments (ab initio)
cufflinks --no-update-check -o "out" reads.sam

# The GTF contains FPKM/confidence values as floating point numbers, which
# may differ slightly between platforms.  Strip them and compare the
# (deterministic) transcript structure with the expected result.
strip_fpkms() {
    sed -E 's/ (FPKM|frac|conf_lo|conf_hi|cov) "[^"]*";//g; s/[[:space:]]+$//'
}
strip_fpkms < "out/transcripts.gtf" > "result.gtf"
strip_fpkms < expected/transcripts.gtf > "expected.gtf"
if ! diff -u "expected.gtf" "result.gtf"; then
    echo "ERROR: assembled transcripts differ from the expected result" >&2
    exit 1
fi
echo "cufflinks assembled the expected transcript"

# 2) cuffcompare: compare the assembly with the reference annotation
cuffcompare -o "cmp" -r ref.gtf "out/transcripts.gtf"
# cuffcompare writes the .tmap file next to the query file
tmap="out/cmp.transcripts.gtf.tmap"
if ! awk -F '\t' 'NR>1 && $3 == "=" { matched=1 } END { exit !matched }' "$tmap"; then
    echo "ERROR: cuffcompare did not find an exact match in $tmap" >&2
    exit 1
fi
echo "cuffcompare classified the assembly as an exact match"

# 3) cuffquant: quantitate expression against the reference annotation
cuffquant --no-update-check -o "quant" -u ref.gtf reads.sam
if [ ! -f "quant/abundances.cxb" ]; then
    echo "ERROR: cuffquant did not produce abundances.cxb" >&2
    exit 1
fi
echo "cuffquant produced abundances.cxb"

echo "functional test passed"
