#!/bin/bash

XSLT_DIR=/usr/share/xml/xgridfit/lib/
RUNSCRIPT=xgridfit.xsl
GPAR=''
QPAR=''
TPAR=''
SPAR=''
APAR=''
BPAR=''
IPAR=''
OPAR=''
OUTEXT=.pe

usage() {
    echo
    echo "usage: xgridfit [options] file.{xgf or xml}"
    echo
    echo "Options:"
    echo " -h        display this help message"
    echo " -a num    size of TrueType stack"
    echo " -b num    delta break value"
    echo " -d        run in debug mode (output file has extension .debug)"
    echo " -g glyph  compile only \"glyph\""
    echo " -i file   file to be input by generated script"
    echo " -o file   file to be output by generated script"
    echo " -q        run in quiet mode"
    echo " -s num    max places in storage area (variables)"
    echo " -t num    max points in twilight zone"
    echo
    echo "Note: Options always override settings in the Xgridfit program file."
    echo
}

parseopts () {
  while getopts ":dqht:s:a:g:b:i:o:" optname
    do
    case "$optname" in
      "d")
        RUNSCRIPT=xgridfit-debug.xsl
        OUTEXT=.debug
        ;;
      "g")
        GPAR=' --stringparam glyph-select '$OPTARG
        ;;
      "q")
        QPAR=' --param silent-mode true()'
        ;;
      "t")
        TPAR=' --stringparam max-twilight-points '$OPTARG
        ;;
      "s")
        SPAR=' --stringparam max-storage '$OPTARG
        ;;
      "a")
        APAR=' --stringparam max-stack '$OPTARG
        ;;
      "b")
        BPAR=' --stringparam delta-break '$OPTARG
        ;;
      "i")
        IPAR=' --stringparam infile '$OPTARG
        ;;
      "o")
        OPAR=' --stringparam outfile '$OPTARG
        ;;
      "h")
        usage
        exit 0
        ;;
      "?")
        usage
        exit 1
        ;;
      ":")
        usage
        exit 1
        ;;
      *)
        echo "mysterious error"
        ;;
    esac
  done
  return $OPTIND
}

runscript () {
    for f in "$@"
      do
      BASENAME=$f
      if [ -z "$BASENAME" ]; then
          usage
          exit 1
      fi
      if echo $BASENAME | grep -q "\.xgf$"
          then
          BASENAME=`basename $BASENAME .xgf`
      elif echo $BASENAME | grep -q "\.xml$"
          then
          BASENAME=`basename $BASENAME .xml`
      fi
      if grep -q "<xgridfit" $f
          then
          xsltproc --xinclude $GPAR$QPAR$TPAR$SPAR$APAR$BPAR$IPAR$OPAR \
              --output ${BASENAME}${OUTEXT} ${XSLT_DIR}${RUNSCRIPT} $f
      else
          echo "File \"$f\" either does not exist or contains no <xgridfit> element."
      fi
  done
}

parseopts "$@"
argstart=$?
runscript "${@:$argstart}"
