#!/bin/sh
profile=default
odd=false
debug=false
header=
conversion=
while test $# -gt 0; do
  case $1 in
    --profile=*)  profile=`echo $1 | sed 's/.*=//'`;;
    --header=*)  header=`echo $1 | sed 's/.*=//'`;;
    --conversion=*)  conversion=`echo $1 | sed 's/.*=//'`;;
    --debug)     debug=true;;
     *) if test "$1" = "${1#--}" ; then 
	   break
	else
	   echo "WARNING: Unrecognized option '$1' ignored"
	   echo "For usage syntax issue $0 --help"
	fi ;;
  esac
  shift
done
test -f "$1" || exit 1
HERE=`pwd`
D=`dirname "$1"`
THERE=`(cd $D; pwd)`
H=`dirname $0`
APPHOME=`(cd $H; pwd)`
N=`basename "$1" .docx`
echo read input file $N from $THERE
echo metadata header file is $header
echo app is in $HERE
if test "x$conversion" = "x"
then
  FROMXSL=$APPHOME/profiles/$profile/docx/from.xsl
else
  FROMXSL=$conversion
fi
echo Using $FROMXSL as conversion XSL
TEMPDIR=/tmp/docx$$
mkdir $TEMPDIR
cd $TEMPDIR
unzip -q $THERE/"$N.docx"
saxon word/document.xml $FROMXSL word-directory=`pwd` metadata-file=$header origfile="$N" origdir="$D" debug=$debug > "$N.xml"
if [ "$(ls -q -A word/media)" ]; then
 echo found graphics files in document, so writing $N.zip
 mv word/media .
 test -d word/embeddings && mv -f word/embeddings .
 test -f $THERE/"$N.zip" && rm $THERE/"$N.zip"
 zip -q -r $THERE/"$N.zip" "$N.xml" media embeddings
else
 echo writing $N.xml
 mv "$N.xml" $THERE
fi
cd $HERE
if $debug 
then
    echo Working files in $TEMPDIR
else
    rm -rf $TEMPDIR
fi
echo wrote $N.xml or $N.zip in $THERE

