#!/bin/sh
#set -x
scriptpath=`dirname $0`
upwd=`pwd`

# Absolute top package path
toppath=`cd $scriptpath/.. && pwd`

# Default Options
ext=pdf
btex=dvips
xopt=""
specs=""
texinputs=""
pdfinputs=""
debug=0
version=0
paritems=""
texstyle=docbook
xsl=$toppath/xsl/latex_book_fast.xsl
xsllst=$toppath/xsl/common/mklistings.xsl
btexpath=$toppath/latex/scripts
tgetpath=$toppath/latex/specs

get_options() {
  while true
  do
    case "$1" in
    -o) dst=$2; shift ;;
    -f) ifig=$2; shift ;;
    -t) ext=$2; shift ;;
    -b) btex=$2; shift ;;
    -x) xopt="$xopt $2"; shift ;;
    -d) debug=1;;
    -s) xsl=$toppath/xsl/latex_book.xsl;;
    -p) param=$2; shift ;;
    -I) xpath=$2; shift ;;
    -S) specs=$2; shift ;;
    -P) paritems="$paritems $2"; shift ;;
    -T) target=$2; shift ;;
    -X) xsllst="";;
    -v) version=1;;
    --style) texstyle=$2; shift ;;
    --texinputs) texinputs=$2; shift ;;
    --pdfinputs) pdfinputs=$2; shift ;;
    --texpost) texpost=$2; shift ;;
    -*) echo "$1: unknown option"; usage;;
    *) break ;;
    esac
    shift
  done

  if [ $# -ne 1 ]; then
    if [ $version -eq 0 ]; then
      usage
    else
      print_version
      exit 0
    fi
  fi
  file=$1
}

show_target() {
  tgets=""
  for i in $tgetpath/*.specs; do
    j=`basename $i .specs`
    if [ "$tgets" = "" ]; then
      tgets="$j"
    else
      tgets="$tgets, $j"
    fi
  done
  echo $tgets
}

usage() {
  tgets=`show_target`
  cat <<eof
`basename $0` [options] file.{sgml|xml}
Options:
-t {pdf|ps|dvi|tex|xml}: output format
-b {pdftex|dvips}      : driver to use
-f {fig|eps}           : input figures format
-d                     : debug mode (keep the temporary dir)
-v                     : display the version number
-o output              : output filename
-p param_file          : XSL parameter file for customization
-P param=value         : single XSL parameter
-s                     : strict latex output (slower)
-S spec_file           : specification file for behaviour customization
-x option              : option passed to the XSLT
-X                     : no external text file support
-I "path1 path2 ..."   : extra files paths
-T style               : available latex styles ($tgets)
eof
  exit 1
}

build_param() {
  param="$1"
  paritems="$2"
  if [ "$param" != "" ]; then
    # Suppose we have absolute path
    param_import="<xsl:import href=\"$param\"/>"
  else
    param_import=""
  fi
  cat <<eof
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:m="http://www.w3.org/1998/Math/MathML"
                version="1.0">

<xsl:import href="$xsl"/>
$param_import
eof
  for p in $paritems; do
    v=`expr "x$p" : 'x[^=]*=\(.*\)'`
    n=`expr "x$p" : 'x\([^=]*\)=.*'`
    echo "<xsl:param name=\"$n\">$v</xsl:param>"
  done
  cat <<eof
<xsl:param name="latex.style">$texstyle</xsl:param>

</xsl:stylesheet>
eof
}

print_version()
{
  ver=`cat $toppath/xsl/version.xsl|grep variable|sed 's/<[^>]*>\([^<]*\)<.*$/\1/'`
  echo "dblatex version $ver"
}

args="$*"

get_options $args

if [ "$specs" = "" ] && [ "$target" != "" ]; then
  if [ -f $tgetpath/$target.specs ]; then
    specs="$tgetpath/$target.specs" 
  else
    echo "Warning: unknown $target specs"
  fi
fi

if [ "$specs" != "" ]; then
  specs_opt=`$toppath/scripts/specsread $specs`;
  get_options $specs_opt $args
fi

# Should we print version number?
if [ "$version" = "1" ]; then
  print_version
fi

# Which make is used? If nothing said gmake is used
[ "$GMAKE" = "" ]  && GMAKE=gmake

# Is there some extra path to add to TEXINPUTS?
if [ "$texinputs" != "" ]; then
  texinputs=`cd $texinputs && pwd`
  TEXINPUTS=":$texinputs//:$TEXINPUTS"
  export TEXINPUTS
fi

# Driver consistency check
case "$ext" in
ps | dvi) if [ "$btex" != "dvips" ]; then
            btex="dvips"
            echo "TeX Backend Driver forced to $btex"
          fi ;;
tex) btex="none" ;;
esac

# Let's check the backend driver and do the appropriate actions
case "$btex" in
pdftex) btexrun=$btexpath/runpdflatex ;
        if [ "$pdfinputs" != "" ]; then
          if [ -d $upwd/$pdfinputs ]; then
            pdfinputs=`cd $pdfinputs && pwd`
          fi
          btexrun="$btexrun --graphpath $pdfinputs"
        fi;;
dvips)  btexrun=$btexpath/runlatex ;;
none)   btexrun="" ;;
*)      echo "$btex: unknown TeX Backend Driver"; usage ;;
esac

# Extra TeX handler to use
if [ "$texpost" != "" ]; then
  if [ -f $upwd/$texpost ]; then
    texpost=$upwd/$texpost
  fi
  btexrun="$btexrun --texpost $texpost"
fi;

basefile=`basename $file`
sgmlfile=`basename $file .sgml`
where=`dirname $file`

# We want the absolute path
where=`cd $where && pwd`
file=$where/$basefile

if [ "$param" != "" ]; then
  bfile=`basename $param`
  path=`dirname $param`
  param=`cd $path && pwd`/$bfile
fi

# Work in a temporary directory
tmpdir=/tmp/tpub-$LOGNAME-$$
mkdir $tmpdir
cd $tmpdir

# Let's convert to XML first if needed
is_xml=`file $file| grep -c "XML"`
if [ $is_xml -eq 0 ]; then
  $toppath/scripts/sgml2xml.pl - $file $sgmlfile.xml
  file=${sgmlfile}.xml
fi

# No path specified, because it's given to gmake via -C
out="`basename $file .xml`.${ext}"

# Where to put the output file
if [ "$dst" = "" ]; then
  dst=$where/$out
elif [ -d `dirname $upwd/$dst` ]; then
  path=`dirname $upwd/$dst`
  bfile=`basename $dst`
  dst=`cd $path && pwd`/$bfile
fi

# XML production only
if [ "$ext" = "xml" ]; then
  if [ "$file" != "$dst" ]; then
    cp $file $dst
  fi
fi
    
# Parameter file building
if [ "$param" != "" ] || [ "$paritems" != "" ] || [ "$texstyle" != "docbook" ]; then
  build_param "$param" "$paritems" > custom.xsl
  xsl="custom.xsl"
fi

# Figure conversion asked by the user
if [ "$ifig" != "" ]; then
  fig2dev=$ifig
fi

# For easy debug
if [ $debug -ne 0 ]; then
  echo "TEXINPUTS=$TEXINPUTS" > $tmpdir/env_tex
  echo "export TEXINPUTS"    >> $tmpdir/env_tex
fi

# PDF/DVI/Postscript production
$GMAKE -s -C $tmpdir -f $toppath/scripts/make.build \
        SRCDIR=$where \
        XPATH="$xpath" \
        XSL=$xsl \
        XSLLST=$xsllst \
        XOPT="$xopt" \
        XMLFILE=$file \
        TEXCLEAN=$toppath/scripts/texclean \
        FIG2DEV=$fig2dev \
        TEXRUN="$btexrun" TEXDRV=$btex $out

rc=$?

if [ $rc -eq 0 ] && [ "$dst" != "$out" ]; then
  mv $out $dst
fi

cd $upwd
if [ $debug -eq 0 ]; then
  rm -r $tmpdir
else
  echo "$tmpdir is not removed"
fi
exit $rc
