#!/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
   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 "ADTTMP.......: ${ADTTMP}"
echo "ADT_ARTIFACTS: ${ADT_ARTIFACTS}"
echo "EPYDOC.......: ${EPYDOC}"
echo "PYTHONPATH...: ${PYTHONPATH}"
echo "========================================================================="
echo ""

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

# Set up some configuration
NAME="Super Duper Special Project"
URL="http://this.is.something/special"
PACKAGE="testpackage"
OUTPUT="${ADTTMP}/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 ""

