#!/bin/sh

PROG=antiword
PAPER=a4

APP_DIR=`dirname $0`
APP_DIR=`cd $APP_DIR;pwd`; export APP_DIR

ARCH=`uname -m`
BIN=/usr/bin/$PROG

case $ARCH in
	i?86) ARCH=ix86 ;;
esac

OS=`uname -s`
PLATFORM=$OS-$ARCH

case $1 in
	--compile)
		shift
		if [ ! -d $APP_DIR/src ] ; then
			echo "ERROR from $0:" >&2
			echo "Cannot compile - source code is missing!" >&2
			exit 1
		fi
		echo "Compiling $APP_DIR... please wait..." >&2
                cd $APP_DIR/src
		make -f Makefile.$OS clean && \
                  make -f Makefile.$OS PLATFORM=$PLATFORM install && \
                  echo Done >&2 && exit 0
		echo Compile failed >&2
		echo Press Return... >&2
		read WAIT
		exit 1
            ;;
        --ascii)
                exec $APP_DIR/Convert
            ;;
esac

BIN=/usr/bin/$PROG

if [ -x $BIN ]; then
  cd $APP_DIR
  ERRFILE=${TMPDIR:-/tmp}/antiword.$$.err
  TMPFILE=${TMPDIR:-/tmp}/antiword.$$

  if [ -n "$1" ]; then
      if [ $PAPER = "text" ]; then
        TMPFILE="$TMPFILE".txt
        $BIN "$@" 2>"$ERRFILE" >"$TMPFILE"
      else
        TMPFILE="$TMPFILE".ps
        $BIN -p $PAPER -i 0 "$@" 2>"$ERRFILE" >"$TMPFILE"
      fi
      result=$?
      if [ $result -ne 0 ]; then
          if [ -s "$ERRFILE" ]; then
              Xdialog --title "Error" --no-cancel \
                --backtitle "Conversion failed. Reason:" \
                --textbox "$ERRFILE" 28 80
          else
              Xdialog --title "Error" --msgbox \
               "Conversion failed for unknown reason!" 0 0
          fi
      else
        if [ $PAPER = "text" ]; then
          ${HOME}/share/apps/Edit/AppRun "$TMPFILE"
        else
	    if which gv 2> /dev/null ; then
		gv "$TMPFILE" -nocentre -media $PAPER
	    elif which ggv 2> /dev/null ; then
		ggv "$TMPFILE"
	    fi
        fi
      fi
      rm -fr "$TMPFILE" "$ERRFILE"
  else
      Xdialog --title "Antiword" --backtitle "Usage notice:" \
        --msgbox "\n\n  Drop a Word Document File  \n  on me to view it!  \n\n" \
        0 0
  fi
else
  echo "ERROR from $0:" >&2
  echo "I cannot find an executable file for your host type ($PLATFORM)." >&2
  echo "Trying to compile..." >&2
  if [ -n "$DISPLAY" ]; then
    xterm -e $0 --compile
  else
    $0 --compile
  fi
  if [ -x $BIN ]; then
    exec $0 "$@"
  fi
  exit 1
fi

