#! /bin/sh

# This script verifies that the XSL defaults expansion mechanism is
# correct by expanding defaults in the set of example files and
# comparing the results with an expanded reference.

# Copyright © 2005-2008 Brendt Wohlberg <photoml@wohlberg.net>
# Please see the PhotoML distribution README file for license information

# Most recent modification: 14 January 2008


catalog="../../../dtd/catalog.xml"
XML_CATALOG_FILES=$catalog
export XML_CATALOG_FILES
photoxsl="../expand.xsl"
doctypub=`grep -o 'doctype-public=\"[^\"]\+\"' $photoxsl | sed 's/doctype-public=//'`


# Do a specified test file
dfltstest()
{
  # Test file
  t=$1
  # Result handling flag
  r=$2
  # Status message
  echo "$t ---------------------------------------------"
  # Files to clean up on exit
  clean="tmpdef.xml tmpref.xml tmpexp.xml"
  # Enable ^C signal handling
  trap "rm -f $clean; exit 1" 2
  # Extract test file components
  def=`cat $t | sed -n '/===def/,/===def/ {/===def/b;p}'`
  ref=`cat $t | sed -n '/===ref/,/===ref/ {/===ref/b;p}'`
  # Write temporary file with defaults
  cat <<EOF > tmpdef.xml
<?xml version="1.0"?>
<!DOCTYPE photo PUBLIC $doctypub "photo.dtd">
$def
EOF
  # Write temporary expanded reference file
  cat <<EOF > tmpref.xml
<?xml version="1.0"?>
<!DOCTYPE photo PUBLIC $doctypub "photo.dtd">
$ref
EOF
  # Initialise failure flag
  fail=0
  # Validate temporary file with defaults
  if ! xmllint --valid --noout tmpdef.xml; then
    fail=1
    echo "Error validating XML with defaults"
  fi
  # Validate temporary expanded reference file
  if ! xmllint --valid --noout tmpref.xml; then
    fail=1
    echo "Error validating expanded reference XML"
  fi
  if [ $fail -eq 0 ]; then
    # Expand defaults
    if [ $r -eq 0 ]; then 
      xsltproc --novalid $photoxsl tmpdef.xml > tmpexp.xml 2>/dev/null
    else
      xsltproc --novalid $photoxsl tmpdef.xml > tmpexp.xml
    fi
    # Check required output handling
    if [ $r -eq 0 ]; then
      # Compare output with test reference
      if ! diff -bB tmpexp.xml tmpref.xml; then
        fail=1
      fi
    else
      # Write result to stdout
      echo "Expand result:"
      echo
      cat tmpexp.xml
      echo
    fi
  fi

  # Clean up
  rm -f $clean
  # Disable ^C signal handling
  trap 'exit 1' 2

  return $fail
}


# If no command line arguments, run all tests 
# otherwise run specified test
fn=0
tn=0
if [ $# -eq 0 ]; then
  if [ "`echo *.t | grep -o '*'`" = '*' ]; then
    echo "No *.t test files found"
    exit 2
  fi
  echo XSL defaults tests
  for t in *.t; do
    if ! dfltstest $t 0; then
      fn=`expr $fn + 1`
    fi
    tn=`expr $tn + 1`
  done 
  echo "Failed $fn out of $tn tests"
else
  if [ -r "$1" ]; then
    dfltstest $1 1
  else
    echo "Could not open file $1"
  fi
fi

if [ "$fn" -gt 0 ]; then
  exit 1
else
  exit 0
fi
