#!/bin/bash

#---------------------------------------------------------------------------
#  LatexDB 0.3  --  enhances LaTeX with database access features
#  Copyright (C) 2003-2006  Hans-Georg Eßer <h.g.esser@gmx.de>
#
#  Contributors:
#  Gerhard Kirchmann <gerhard.kirchmann@arcor.de>:
#    PostgreSQL code and code cleanup (using Cursors)
#  Francois Meyer <fmeyer@obs-besancon.fr>
#    Fix for a problem with recursion in the preparser
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  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.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#---------------------------------------------------------------------------


LATEXDBVERSION="0.3"
LATEXDBRELEASE="2006/04/24"

pretex=$1
latexdbpy=`echo $0.py | sed -e "s/pdflatex/latex/"`
latexdbpre=`echo $latexdbpy | sed -e "s/latexdb.py/latexdb-preparse.py/"`

if [ "x$pretex" == "x" ]; then
  echo $0: error, you must supply a .tex file name
  exit -1
fi

# help
if [ $pretex == "-h" ]; then
  echo "Syntax: $0 file.tex"
  echo "Note that you must supply the .tex ending, other than with the"
  echo "latex command which accepts 'latex file' to go for file.tex."
  exit 0
fi

# version info
if [ $pretex == "-v" ]; then
   echo "$0 version $LATEXDBVERSION ($LATEXDBRELEASE)."
   echo "Relased under the GPL."
fi

# set loop counter. we count how often laxexdb.py is called
LOOP=1

if [ -f $pretex ]; then
  cp $pretex $pretex.backup
  DONE=0
  while [ "$DONE" = "0" ]; do
    # This is one loop
    echo Pre-Compiling $pretex \(loop $LOOP\);
    cp $pretex $pretex.texdb.$LOOP
    $latexdbpre < $pretex.texdb.$LOOP > $pretex.pre.$LOOP
    $latexdbpy < $pretex.pre.$LOOP > $pretex.$LOOP
    cp $pretex.$LOOP $pretex
    if [ $? != 0 ]; then
      echo "Error occurred while pre-compiling.";
      mv -f $pretex.texdb $pretex
      exit -1;
    fi
    # Test if another loop is necessary
    grep '\\texdbdef' $pretex > /dev/null
    # grep will make $? 1 if no \texdbdef command is found
    DONE=$?
    let LOOP="LOOP+1"  # increase loop counter
    # end of loop
  done

  # call latex with all options from the dblatex command line
  pdflatex $@
  mv -f $pretex.backup $pretex

  # clean up (we dont, cause we debug)
  # rm -f $pretex.tex.* $pretex.tex.pre.* $pretex.tex.texdb.*
fi

