#! /bin/sh
#
# $Header: /cvs/rjkdoc/install-sgml-cat,v 1.1 2000/01/27 13:03:20 richard Exp $
#

set -e

defcat=/etc/sgml.catalog

help() {
  echo "install-sgml-cat: Usage:"
  echo ""
  echo "  install-sgml-cat [-C] [-v] [-r] [-c CATFILE] -- PUBID FILENAME ..."
  echo "  install-sgml-cat -h"
  echo "  install-sgml-cat -V"
  echo ""
  echo "--create, -C         Create catalog if it does not exist"
  echo "--verbose, -v        Verbose mode"
  echo "--replace, -r        Replace existing entries"
  echo "--catalog, -c        Set catalog to modify (default: ${defcat})"
  echo "--help, -h           Display usage information"
  echo "--version, -V        Display version information"
}

version() {
  echo "install-sgml-cat 0.1"
}

verb() {
  if test $verbose = 1; then
    echo "$@"
  fi
}

catalog="${defcat}"
replace=0
verbose=0
create=0

while test $# -gt 0; do
  arg="$1"
  shift
  case "${arg}" in
  --help | -h )
    help
    exit 0
    ;;
  --version | -V )
    version
    exit 0
    ;;
  --verbose | -v )
    verbose=1
    ;;
  --catalog | -c )
    catalog="$1"
    shift
    ;;
  --replace | -r )
    replace=1
    ;;
  --create | -C )
    create=1
    ;;
  -- | - )
    break
    ;;
  -* )
    echo "install-sgml-cat: unknown option '${arg}'" 1>&2
    exit 1
    ;;
  esac
done

if test ! -f "${catalog}"; then
  if test ${create} = 1; then
    verb "Creating ${catalog}"
    echo "# ${catalog}" > ${catalog}
  else
    echo "install-sgml-cat: ${catalog} does not exist and --create was not specified" 1>&2
    exit 1
  fi
fi

# scan the list of pubid/filename pairs
while test $# -gt 1; do
  pubid="$1"
  filename="$2"
  shift
  shift
  # add quotes back in
  pubid_q="\"${pubid}\"" 
  # quote for egrep
  pubid_gq=`echo "${pubid_q}"|sed 's/[^a-zA-Z0-9 ]/\\\&/g'`
  # see if there is already an entry for this PUBID
  if egrep "^PUBLIC[ \t]+${pubid_gq}[ \t]+.+" "${catalog}" > /dev/null 2>&1
  then
    present=1
  else
    present=0
  fi
  # if --replace was not specified, we leave existing entries alone
  if test ${present} = 1 && test ${replace} = 0; then
    verb "Skipping ${pubid_q} (already present)"
    continue
  fi
  # create a temporary file with the same permissions as the master
  cp -p "${catalog}" "${catalog}.tmp"
  if test ${present} = 1; then
    verb "Replacing ${pubid_q}"
    egrep -v "^PUBLIC[ \t]+${pubid_gq}[ \t]+.+" "${catalog}" > "${catalog}.tmp"
  else
    verb "Adding ${pubid_q}"
  fi
  echo "PUBLIC ${pubid_q} ${filename}" >> "${catalog}.tmp"
  mv "${catalog}.tmp" "${catalog}"
done

if test $# -gt 0; then
  echo "install-sgml-cat: bogus final argument '$1'" 1>&2
  exit 1
fi

exit 0
