#!/bin/bash
# 
# Copyright (C) 2001-2005 Michael Fuchs
#

prog=`type -p -- $0`

if [ $? -ne 0 ] ; then
    echo "Can't find installation directory!"
    exit 1
fi

prog=`readlink -f $prog`
bindir=`dirname "$prog"`

dbdhome=`cd "$bindir/.." && pwd`
[ ! -d $dbdhome ] && fatal "Can't find directory $dbdhome!"

function fatal {
    echo "[Error] $1"
    exit 1
}

function usage {

    msg=$1
    cat <<EOF
Syntax: dbdcref class

Examples:
  dbdcref org/dbdoclet/doclet/docbook/DocBookDoclet.java

EOF

    [ "$msg" != "" ] && fatal "$msg"
    
    exit 0
}

sourcepath=""
destdir="man"
packages=""

counter=0

while [ $# -gt 0 ]
do
  case $1 in

      -d)  
          destdir=$2
          shift
	  ;;

      -s)  
          sourcepath="-sourcepath $2"
          shift
	  ;;
      
      *) 
          packages[$counter]=$1
          counter=$(($counter+1))
	  ;;
  esac
  shift
done

if [ "x${destdir}" = "x" ] ; then
    usage "Please specify a destination directory!"
fi

if [ ${counter} -eq 0 ] ; then
    usage "Please specify a package!"
fi

install -d $destdir

tmpDir=`mktemp -d`

$dbdhome/bin/dbdoclet \
    -nostatistics \
    -noindex \
    -noconstants \
    -booktype reference \
    -split \
    -d $tmpDir \
    $sourcepath \
    "${packages[@]}"

[ $? -ne 0 ] && exit -1

rm $tmpDir/Reference.xml
[ $? -ne 0 ] && exit -1

for f in $tmpDir/*.xml; do

    fofile=${f%%.xml}.fo
    cname=`basename $f .xml`

    $dbdhome/bin/dbdxslt -i $f -t fo  -o ${fofile}
    [ $? -ne 0 ] && exit -1

    $dbdhome/bin/dbdfop -i ${fofile} -t pdf -o ${destdir}/${cname}.pdf
    [ $? -ne 0 ] && exit -1

done

# rm -rf $tmpDir
exit 0
