#!/bin/sh
set -e

pkg=ltrsift

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}/sample_data "${AUTOPKGTEST_TMP}"

cd "${AUTOPKGTEST_TMP}"

TMP="${AUTOPKGTEST_TMP:-$(mktemp -d)}"
export HOME="$TMP/home"
export XDG_CONFIG_HOME="$HOME/.config"
export XDG_CACHE_HOME="$HOME/.cache"
export GDK_BACKEND=x11
mkdir -p "$XDG_CONFIG_HOME" "$XDG_CACHE_HOME"

# Exercise the non-GUI encoder on a small sequence.
cat > "$TMP/test.fa" <<EOF
>chr1
ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGT
EOF
ltrsift_encode "$TMP/test.fa" "$TMP/index"
test -f "$TMP/index.esq"

# Run the example provided upstream
cd sample_data/
sh ./prepare_encseqs

# Start the GUI under Xvfb and make sure it stays alive. A timeout means the
# main loop is running, which is the expected outcome of this smoke test.
set +e
xvfb-run -a timeout 10 ltrsift > "$TMP/ltrsift.log" 2>&1
status=$?
set -e
if [ "$status" -ne 124 ]; then
    cat "$TMP/ltrsift.log" >&2
    echo "FAIL: ltrsift exited unexpectedly with status $status" >&2
    exit 1
fi
