#! /bin/sh

# This script verifies that the XSL merge function/template is
# correct by merging subtrees the set of example files and
# comparing the results with reference subtrees.

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

# Most recent modification: 14 January 2008


# Do a specified test file
mergetest()
{
  # Test file
  t=$1
  # Result handling flag
  r=$2
  # Status message
  echo "$t ---------------------------------------------"
  # Files to clean up on exit
  clean="tmp.dtd tmp0.xml tmp1.xml tmp2.xml valid.xsl"
  # Enable ^C signal handling
  trap "rm -f $clean; exit 1" 2
  # Extract test file components
  dtd=`cat $t | sed -n '/===dtd/,/===dtd/ {/===dtd/b;p}'`
  x=`cat $t | sed -n '/===x/,/===x/ {/===x/b;p}'`
  y=`cat $t | sed -n '/===y/,/===y/ {/===y/b;p}'`
  z=`cat $t | sed -n '/===z/,/===z/ {/===z/b;p}'`
  # Extract content model from DTD component
  elt=`echo "$dtd" | grep -o -E '<!ELEMENT [^ ]+' | sed -s 's/<!ELEMENT //' | xargs | sed -s 's/ /,/g'`
  echo "$dtd" > tmp.dtd
  # Build XSLT content model validation template
  dtdto --valid tmp.dtd > valid.xsl
  # Write subtrees to be merged to a temporary file
  cat <<EOF > tmp0.xml
<?xml version="1.0"?>
<test>
<x>
  $x
</x>
<y>
  $y
</y>
</test>
EOF
  # Write merge reference subtree to a temporary file
  cat <<EOF > tmp1.xml
<?xml version="1.0"?>
$z
EOF
  # Do merge
  if [ $r -eq 0 ]; then
    xsltproc mtest.xsl tmp0.xml > tmp2.xml 2>/dev/null
  else
    xsltproc mtest.xsl tmp0.xml > tmp2.xml
  fi
  # Initialise failure flag
  fail=0
  # Check required output handling
  if [ $r -eq 0 ]; then
    # Compare output with test reference
    if ! diff -bB tmp1.xml tmp2.xml; then
      fail=1
    fi
  else
    # Write result to stdout
    echo "Merge result:"
    echo
    cat tmp2.xml
    echo
  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 merge tests
  for t in *.t; do
    if ! mergetest $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
    mergetest $1 1
  else
    echo "Could not open file $1"
  fi
fi

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