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

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

# Set up some file and directory locations 
PROJECT="${ADTTMP}/project"
CONFIG="${ADTTMP}/config"
SOURCE="${ADTTMP}/source"
GTP="${PROJECT}/project.gtp"
MAKEFILE="${ADTTMP}/Makefile"

# Copy in the project directory
echo "Creating project in ${PROJECT}..."
mkdir -p ${PROJECT}
cp -r ${SOURCE_TREE}/debian/tests/data/project/config ${CONFIG}
cp -r ${SOURCE_TREE}/debian/tests/data/project/source ${SOURCE}

# Create the project.gtp file, which requires an absolute include path
echo "Creating GTP file: ${GTP}..."
rm -f ${GTP}
echo "define INCLUDE_PATH ${CONFIG}" >> ${GTP}
echo "allsource" >> ${GTP}

# Create the GTML makefile
echo "Creating Makefile: ${MAKEFILE}..."
${GTML} -M${MAKEFILE} ${GTP}
if [ $? != 0 ]; then
   echo "Error: failed to create GTML makefile."
   exit 1
elif [ ! -f ${MAKEFILE} ]; then
   echo "Error: GTML apparently did not generate Makefile"
   exit 1
fi

# Build the site
echo "Making the project...."
/usr/bin/make
if [ $? != 0 ]; then
   echo "Make failed."
   exit 1
fi

# Check that every expected file exists and matches expectations
echo "Confirming expected results..."
for EXPECTED in ${SOURCE_TREE}/debian/tests/data/project/expected/*.html; do
   ACTUAL="${SOURCE}/`basename ${EXPECTED}`"
   echo "diff -Naur ${EXPECTED} ${ACTUAL}"
   /usr/bin/diff -Naur ${EXPECTED} ${ACTUAL}
   if [ $? != 0 ]; then
      echo "Generated result differs."
      exit 1
   fi
done
echo "Actual results match expected results... success!"

# Close the test
echo ""

