#!/bin/sh
# -*- Mode: sh -*-
# File: $CVSROOT/IDEA-DEV/XIDDL/build-xiddl
# Info: $CVSROOT/IDEA-DEV/COPYRIGHT
#  CVS: $Id: build-xiddl,v 1.5 2005/12/30 22:48:47 rijsman Exp $

usage ()
{
  echo " "
  echo "usage: build-xiddl <master-xiddl> <xiddl-output> <error-output> [debug]"
  echo " "
}

if [ ! $# -eq 3 ] && [ ! $# -eq 4 ]
then
  usage
  exit
elif [ ! -e $1 ]
then
  echo " "
  echo "master xiddl file '$1' not found."
  echo " "
  exit -1
fi

if [ "$1" == "$2" ]
then
  echo " "
  echo "master (agent) file and combined file must have differenct names."
  echo " "
  exit -1
fi

temp_error_file=$3

if [ "$4" = "" ]
then
  debug=0
else
  debug=1
fi

# get the "model" file names
xiddl_files=`(ls *.xiddl)`

# generate the "temp model" files which include the file name and line
# numbers (so the tests can report file name and line numbers)
for file in $xiddl_files
do
  cat $file \
  | awk '$0 !~ /<[^?/\!][^:/>]+\/?>/ { print }
               /<[^?/\!][^:/>]+\/?>/ { gsub(/<[^/\!][^/>]+/,
                          "& file=\"'$file'\" line=\"" NR "\"") ; print }' \
  > $file.temp
done

# generate the "temp agent" file from $1.temp (this fixes the include
# directives if there are any)
cat $1.temp | awk '{ sub(/\.xiddl#/, ".xiddl.temp#") ; print }' > $1.temp.temp

# and rename the temp files without overwriting everthing
mv $1.temp.temp $1.temp

# generate the file to be used for semantic checking and feedback
# (by processing the include directives)
xmllint --xinclude --format $1.temp 1> $2.temp 2>$temp_error_file.temp

# clean up the unneeded temp files
for file in $xiddl_files
do
  if [ $2 != $file ] && [ $debug != 1 ]
  then
    rm $file.temp
  fi
done

# report any xmllint errors
egrep "error:|XInclude:" $temp_error_file.temp

# generate the "real" xiddl model without the file names and line
# numbers.
xmllint --xinclude --format $1 1> $2 2>$temp_error_file
# check for any errors that need to be fixed
errors=`egrep "error:|XInclude:" $temp_error_file | wc | awk '{ print $1 }'`

egrep "error:" $temp_error_file

if [ "$errors" -ne '0' ];
then
  echo " "
  echo "xml/xiddl errors found.  see $temp_error_file for further details."
  echo " "
  exit -1
fi

if [ $debug = 0 ]
then
  rm $temp_error_file $temp_error_file.temp
fi

exit 0

#  EOF
