#!/bin/sh

# Make sure $AUTOPKGTEST_TMP is available
if [ "${AUTOPKGTEST_TMP}"F = "F" ]; then
   echo "Error: expected environment variable AUTOPKGTEST_TMP is not set."
   exit 1
fi

# Make sure $AUTOPKGTEST_ARTIFACTS is available
if [ "${AUTOPKGTEST_ARTIFACTS}"F = "F" ]; then
   echo "Error: expected environment variable AUTOPKGTEST_ARTIFACTS is not set."
   exit 1
fi

# Determine the test execution mode 
if [ "${1}"F = "F" ]; then
   MODE="autopkgtest"
elif [ "${1}" = "-r" ]; then
   MODE="debian/rules"
else 
   echo "usage: $0 [-r]\n-r Run in debian/rules mode instead of autopkgtest mode"
   exit 2
fi

# Determine locations of required tools
SOURCE_TREE="${PWD}"
if [ "${MODE}" = "debian/rules" ]; then
   # In debian/rules mode, the executables are assumed to be in the source tree
   COMPRESS="${PWD}/compress"
   UNCOMPRESS="${PWD}/compress -d"
   DIFF="/usr/bin/diff"
else
   # In autopkgtest mode, the executables are assumed to be installed
   COMPRESS="/usr/bin/compress"
   UNCOMPRESS="/usr/bin/uncompress.real"
   DIFF="/usr/bin/diff"
fi

# Print a test summary
echo ""
echo "========================================================================="
echo "Running ${0} in mode: ${MODE}"
echo "========================================================================="
echo "SOURCE_TREE..........: ${SOURCE_TREE}"
echo "AUTOPKGTEST_TMP......: ${AUTOPKGTEST_TMP}"
echo "AUTOPKGTEST_ARTIFACTS: ${AUTOPKGTEST_ARTIFACTS}"
echo "COMPRESS.............: ${COMPRESS}"
echo "UNCOMPRESS...........: ${UNCOMPRESS}"
echo "DIFF.................: ${DIFF}"
echo "========================================================================="
echo ""

# Always run tests from within $AUTOPKGTEST_TMP
cd ${AUTOPKGTEST_TMP}

# Create an input file
echo -n "Creating input file..."
SAMPLE=${SOURCE_TREE}/debian/tests/data/sample.txt

cp ${SAMPLE} input >/dev/null 2>&1
if [ $? != 0 ]; then
   echo "failed"
   exit 1
fi

echo "done."

# Compress the input file
echo -n "Compressing the input file..."

${COMPRESS} input >/dev/null 2>&1
if [ $? != 0 ]; then
   echo "failed"
   exit 1
fi

if [ ! -f input.Z ]; then
   echo "failed: did not get expected output file input.Z"
   exit 1
fi

echo "done."

# Check that uncompress works
echo -n "Checking uncompress behavior..."

${UNCOMPRESS} input.Z >/dev/null 2>&1
if [ $? != 0 ]; then
   echo "failed"
   exit 1
fi

if [ ! -f input ]; then
   echo "failed: did not get expected output file input"
   exit 1
fi

${DIFF} -q ${SAMPLE} input >/dev/null 2>&1
if [ $? != 0 ]; then
   echo "failed: uncompressed file does not match original sample"
   exit 1
fi

echo "done."

# Close the test
echo ""

