#!/bin/sh

prefix=${DESTDIR}/usr/local
exec_prefix=${prefix}
datadir=${prefix}/share
TMPDIR=`mktemp -d /tmp/wvWare.XXXXXXXXXX`
export TMPDIR

# argument checking
if [ ${#} -ne "2" ]; then
	echo "Usage: ${0} <word document> <text output file>"
	exit 1
fi

# start out optimistic
USING_LYNX=1
which lynx >/dev/null 2>&1
if [ ${?} -ne "0" ]; then
	echo "Could not find required program 'lynx'"
	echo "Not using lynx. Ouput will be pretty bad."
	USING_LYNX=0
fi

if [ ${USING_LYNX} -ne "0" ]; then

    # first, test for wvHtml
    which wvHtml >/dev/null 2>&1
    if [ ${?} -ne "0" ]; then
       	echo "Could not find required program 'wvHtml'"
	exit 1
    fi

    # intermediate file
    TMP_FILE="wv$$.html"

    wvHtml "${1}" --targetdir="${TMPDIR}" "${TMP_FILE}" >/dev/null 2>&1
    if [ ${?} -ne "0" ]; then
	echo "Could not convert into HTML"
	exit 1
    fi

    # lynx actually does quite well
    TERM=vt100 lynx -dump -force_html "${TMPDIR}/${TMP_FILE}" > "${2}"
    if [ ${?} -ne "0" ]; then
	    echo "Could not convert into Text"
	    exit 1
    fi

    # clean up
    rm -f "${TMPDIR}/${TMP_FILE}"

else
    # fall back onto our cruddy output
    # this is, admittedly, better than running
    # 'strings' on the word document though :)
    wvWare -x ${datadir}/wv/wvText.xml "${1}" > "${2}"
fi

rm -rf ${TMPDIR}
