#!/bin/bash

abspath() {
  PATH_REL_DIRNAME=`dirname "$1"`
  PATH_ABS_DIRNAME=`cd "$PATH_REL_DIRNAME"; pwd`
  PATH_BASENAME=`basename "$1"`
  if [ "$PATH_BASENAME" == "." ]; then
    echo "$PATH_ABS_DIRNAME" 
  else
    echo "$PATH_ABS_DIRNAME/$PATH_BASENAME" 
  fi
}

if [ -z "$1" ]; then
  echo You must specify a DocBook XML source file as the first command argument
  exit 1
fi

if [ ! -z "$2" ]; then
  TYPE=$2
else
  TYPE=pdf
fi

PRG_DIR=`dirname "$0"`
PRG_ABS_DIR=`abspath "$PRG_DIR"`
GRADLEW_CMD="$PRG_DIR/gradlew"
FOPDF_DIR="${PRG_DIR}/build/fopdf"
FOPDF_ABS_DIR="$PRG_ABS_DIR/build/fopdf"
FOPDF_CMD="$FOPDF_DIR/bin/fopdf"

if [ ! -e "$FOPDF_CMD" ]; then
  echo Initializing application...
  "${GRADLEW_CMD}" -q -u installApp 
  if [ $? != 0 ]; then
    echo Failed to initialize application
    exit 1
  fi
  echo Application initialized!
fi

SOURCE_FILE="$1"
SOURCE_EXTENSION="${SOURCE_FILE##*.}"

if [ "$SOURCE_EXTENSION" != "xml" ] && [ "$SOURCE_EXTENSION" != "fo" ]; then
  echo Illegal source file name: "$SOURCE_FILE"
  echo "Source file must end in .fo (XSL-FO) or .xml (DocBook)"
  exit 1
fi

SOURCE_ROOTNAME="${SOURCE_FILE%.*}"
OUT_FILE="$SOURCE_ROOTNAME.$TYPE"

DOCBOOK_DIR="$FOPDF_DIR/docbook"
DOCBOOK_XSL_DIR="$FOPDF_DIR/docbook-xsl"
DOCBOOK_XSL_ABS_DIR="$FOPDF_ABS_DIR/docbook-xsl"
XSLTHL_CONFIG_URI="file://$DOCBOOK_XSL_ABS_DIR/xslthl-config.xml"

CONVERT_ARGS="-$SOURCE_EXTENSION \"$SOURCE_FILE\""

if [ "$SOURCE_EXTENSION" == "xml" ]; then
  CONVERT_ARGS="$CONVERT_ARGS -xsl \"$DOCBOOK_XSL_DIR/fo-pdf.xsl\""
fi

case $TYPE in
  pdf|ps)
    CONVERT_ARGS="$CONVERT_ARGS -$TYPE \"$OUT_FILE\""
  ;;
  fo)
    CONVERT_ARGS="$CONVERT_ARGS -foout \"$OUT_FILE\""
  ;;
  *)
    echo Unexpected output type: "$TYPE"
    echo Valid options: pdf, ps, fo
    exit 1
  ;;
esac

eval $FOPDF_CMD -q -catalog \
  -c \"$DOCBOOK_XSL_DIR/fop-config.xml\" \
  $CONVERT_ARGS \
  -param highlight.xslthl.config \"$XSLTHL_CONFIG_URI\" \
  -param admon.graphics.path \"$DOCBOOK_DIR/images/\" \
  -param callout.graphics.path \"$DOCBOOK_DIR/images/callouts/\"

exit 0
