#!/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
   EPYDOC="${SOURCE_TREE}/scripts/epydoc"
   export PYTHONPATH="${SOURCE_TREE}"
else
   # In autopkgtest mode, the executables are assumed to be installed
   EPYDOC="/usr/bin/epydoc"
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 "EPYDOC...............: ${EPYDOC}"
echo "PYTHONPATH...........: ${PYTHONPATH}"
echo "========================================================================="
echo ""

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

# Set up some configuration
NAME="Super Duper Special Project"
URL="http://this.is.something/special"
PACKAGE="testpackage"
OUTPUT="${AUTOPKGTEST_TMP}/output"

# Copy in the sample source tree
echo "Creating Python project..."
cp -r ${SOURCE_TREE}/debian/tests/data/htmldocs/testpackage .

# Generate the documentation
echo "Running: ${EPYDOC} --no-include-build-time -v --html --name "${NAME}" --output "${OUTPUT}" --url "${URL}" ${PACKAGE}/"
${EPYDOC} --no-include-build-time -v --html --name "${NAME}" --output "${OUTPUT}" --url "${URL}" ${PACKAGE}/
if [ $? != 0 ]; then
   echo "Error: epydoc command failed"
   exit 1
fi

# Check that the generated results match expected
/usr/bin/diff -Naur ${SOURCE_TREE}/debian/tests/data/htmldocs/expected/output ${OUTPUT}
if [ $? != 0 ]; then
   echo "Generated result differs."
   exit 1
fi
echo "Actual results match expected results... success!"

# Close the test
echo ""

