#! /bin/sh

# This script provides a grep-like utility for PhotoML files

# Copyright © 2003-2007 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: 14 January 2008


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

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

usage()
{
cat <<EOF >&2
usage: pmlgrep [-h] [-e] [-p] [-x xpath] [-s regex] ... [-s regex] 
               infile [infile] ...
       -h        Display usage information
       -e        Expand defaults before searching
       -p        Use perl regular expressions
       -x xpath  Find nodes matching xpath
       -s regex  Find nodes matching custom syntax used by xgrep
EOF
}

xflags=''
expand=0
while [ $# -ge 1 ]; do
  case $1 in
    -e)    expand=1 ;;
    -p)    xflags="$xflags -p" ;;
    -x)    shift; xflags="$xflags -x $1" ;;
    -s)    shift; xflags="$xflags -s $1" ;;
    -*)    usage; exit 1 ;;
    *)     break ;;
  esac
  shift
done   

if [ "$1" = '' ]; then
  usage; 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 [ $expand -eq 1 ]; then
  tmpfile="/tmp/pmlgrep.$$"
  for src in $@; do
    if [ ! -f "$src" -o ! -r "$src" ]; then
      echo "pmlgrep: could not open file $src" >&2
      exit 1
    fi
    xsltproc -o $tmpfile $xsl $src
    xgrep -c "$pmlpath/dtd/catalog.xml" $xflags $tmpfile
  done
  rm -f $tmpfile
else
  xgrep -c "$pmlpath/dtd/catalog.xml" $xflags $@
fi

exit 0
