#!/bin/sh
#

usage="\
Usage: gtkdoc-mkpdf [--path=SEARCH_PATH] [--imgdir=DIR] MODULE DRIVER_FILE [BACKEND_OPTIONS...]"

#echo "args $0\n";

cleanexit() {
  rm -f $module.fo
  exit $1
}

# parse options, ignore unknown options for future extensions

searchpath=
uninstalled=no
imgdirs=
while true; do
    case "X$1" in
        X--version) echo "1.16"; exit 0;;
        X--help) echo "$usage"; exit 0;;
        X--uninstalled) uninstalled=yes; shift;;
        X--path=*) searchpath=`echo $1 | sed s/.*=//`; shift;;
        X--imgdir=*) imgdirs="$imgdirs -I `echo $1 | sed s/.*=//`"; shift;;
        X--*) shift;;
        X*) break;;
    esac
done
 
if test $# -lt 2; then
      echo "${usage}" 1>&2
      exit 1
fi

module=$1
shift
document=$1
shift

if test $uninstalled = yes; then
      # this does not work from buiddir!=srcdir
      # we could try this
      # MAKE_SCRDIR=$(abs_srcdir) MAKE_BUILDDIR=$(abs_builddir) gtkdoc-mkpdf ...
      gtkdocdir=`dirname $0`
      #echo "uninstalled, gtkdocdir=$gtkdocdir"
else
      # the first two are needed to resolve datadir
      prefix=/usr/local
      datarootdir=${prefix}/share
      gtkdocdir=${datarootdir}/gtk-doc/data
fi

if head -n 1 $document | grep "<?xml" > /dev/null; then
  is_xml=true
  path_option='--path'
else
  is_xml=false
  path_option='--directory'
fi

# we could do "$path_option $PWD "
# to avoid needing rewriting entities that are copied from the header
# into docs under xml
if test "X$searchpath" = "X"; then
    path_arg=
else
    path_arg="$path_option $searchpath"
fi

if $is_xml; then
  if test -n ""; then
    # extra options to consider
    # -I FIG_PATH
    # -V is useful for debugging
    # -T db2latex : different style
    # -d : keep transient files (for debugging)
    # xsltproc is already called with --xinclude
    # does not work: --xslt-opts "$path_arg --nonet $@"
    #echo "calling:  -o $module.pdf $imgdirs $document"
     2>&1 -o $module.pdf $imgdirs $document | \
      grep -v "not supported in programlisting or screen"
  else
    if test -n ""; then
      /usr/local/bin/xsltproc $path_arg --nonet --xinclude \
          --stringparam gtkdoc.bookname $module \
          --stringparam gtkdoc.version "1.16" \
          "$@" -o $module.fo $gtkdocdir/gtk-doc-fo.xsl $document || cleanexit $?
      # fop dies too easily :(
      #  $module.fo $module.pdf
    fi
  fi
else
  # not very good output
  # also for xxx-docs.sgml it will produce xxx-docs.pdf
  docbook2pdf -e no-valid $document
fi

echo "timestamp" > pdf.stamp
cleanexit 0

