#! /bin/sh

# This script expands defaults elements in PhotoML files

# Copyright © 2003-2010 Brendt Wohlberg <photoml@wohlberg.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License at
# http://www.gnu.org/licenses/gpl-2.0.txt.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.

# Most recent modification: 18 April 2010


pmlpath="`echo $0 | sed -e 's|/pmlexpand||'`/.."

if [ ! "`which xsltproc 2>/dev/null`" ]; then
  echo "pmlexpand: error executing xstlproc" >&2
  exit 1
fi

usage()
{
cat <<EOF >&2
usage: pmlexpand [-h] [-a | -b] infile [outfile]
       -h  Display usage information
       -a  Replace defaults elements with a comment indicating the 
           position from which they were removed.
       -b  Comment out the defaults elements.
EOF
}

xslparam=''
while [ $# -ge 1 ]; do
  case $1 in
    -a)    xslparam='--stringparam replacement-policy indicate' ;;
    -b)    xslparam='--stringparam replacement-policy comment' ;;
    -*)    usage; exit 1 ;;
    *)     infile=$1; outfile=$2; break ;;
  esac
  shift
done

if [ "$infile" = '' ]; then
  usage; exit 1
fi

if [ ! -f "$infile" -o ! -r "$infile" ]; then
  echo "pmlexpand: could not open file $infile" >&2
  exit 1
fi

dtdpub=`grep DOCTYPE $infile | grep -o -e '-\/\/.*EN'`;
dtdtyp=`echo $dtdpub | grep -o -e '//DTD[^/]*//' | cut -d ' ' -f 2`
if [ "$dtdtyp" != 'PhotoML' ]; then
  echo "pmlexpand: input document type not recognised" >&2 
  exit 1
fi

xsl=$pmlpath/xsl/defaults/expand.xsl

if [ -r /etc/xml/catalog -a "$XML_CATALOG_FILES" = '' ]; then
  XML_CATALOG_FILES=/etc/xml/catalog
fi
XML_CATALOG_FILES="$pmlpath/dtd/catalog.xml $XML_CATALOG_FILES"
export XML_CATALOG_FILES
unset SGML_CATALOG_FILES

if [ "$outfile" = '' ]; then
  xsltproc $xslparam $xsl $infile
else
  xsltproc -o $outfile $xslparam $xsl $infile
fi

exit $?
