#!/bin/sh

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

# Make sure $ADT_ARTIFACTS is available
if [ "${ADT_ARTIFACTS}"F = "F" ]; then
   echo "Error: expected environment variable ADT_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"
   GZIP="/bin/uncompress"
else
   # In autopkgtest mode, the executables are assumed to be installed
   COMPRESS="/usr/bin/compress"
   UNCOMPRESS="/usr/bin/uncompress.real"
   DIFF="/usr/bin/diff"
   GZIP="/bin/uncompress"
fi

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

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

# 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 for compatibility by uncompressing the input file with the gzip uncompress
echo -n "Checking for compatibility with gzip..."

${GZIP} 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 input ${SAMPLE} >/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 ""

