#!/bin/bash
# 

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: dbdman -d man1 -s sourcepath package package package

Examples:
  dbdman -s /home/dbdoclet/src1:/home/dbdoclet/src2 org.dbdoclet.docbook org.dbdoclet.tag

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

for f in $tmpDir/*.xml; do

    echo "Creating manpage for class `basename $f .xml`..."
    $dbdhome/bin/dbdxslt -i $f -t man -o $f.log
    [ $? -ne 0 ] && echo "Creation of manpage `basename $f .xml` failed!"
done

for f in $tmpDir/*.3; do
    echo "Copying manpage `basename $f .3` to $destdir..."
    manpage=${f##*_}
    cp $f $destdir/$manpage
    [ $? -ne 0 ] && fatal "Copying manpage $manpage failed!"
    gzip $destdir/$manpage
    [ $? -ne 0 ] && fatal "Gzip of manpage $manpage failed!"
done

rm -rf $tmpDir

exit 0
