#! /bin/sh
#
# This is a kludge to fix helper apps in mozilla.  See mozilla bugs #57420
# and also #78919.
#
# It's also useful for tar files with Netscape 4.x
#
# Copyright (c) 2002-2003  Paul Vojta
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL PAUL VOJTA OR ANY OTHER AUTHOR OF OR CONTRIBUTOR TO
# THIS SOFTWARE BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.

NO_RM=
TMP_DIR=
progname=xdvizilla

do_cleanup()
{
    [ -z "$NO_RM" ] && rm -f "$ARG"
    [ -n "$TMP_DIR" ] && rm -rf "$TMP_DIR"
}

do_abort()
{
    xmessage -nearmouse "$progname: $1"
    do_cleanup
    exit 1
}

setup_dir()
{
    if [ -z "$TMP_DIR" ]; then
	# Create a temporary directory only read/writable by user
	TMP_DIR=${TMP-/tmp}/$progname.$$
	(umask 077; mkdir "$TMP_DIR") || \
	  do_abort "Could not create directory \`$TMP_DIR'"
	trap 'do_cleanup' 1 2 3 7 13 15
    fi
}

if [ $# -gt 1 -a "x$1" = "x-no-rm" ]; then
    NO_RM=y
    shift
fi

if [ $# -ne 1 ]; then
    xmessage -nearmouse "Usage: $progname [-no-rm] <file>"
    exit 1
fi

DIR=`dirname "$0"`

if [ "$DIR" = . ]; then
    DIR=
elif [ -f "$DIR"/xdvi -a -x "$DIR"/xdvi ]; then
    DIR="$DIR"/
else
    DIR=
fi

ARG=$1
FILE=$1
FILETYPE=`file "$FILE"`
UNCOMP=

case "$FILETYPE" in

    *"gzip compressed data"*)
	UNCOMP=gunzip
	;;

    *"compressed data"* | *"compress'd data"*)
	UNCOMP=uncompress
	;;

    *": empty")
	do_abort "$1 is an empty file
(this is a bug in Mozilla)"
	;;

esac

if [ -n "$UNCOMP" ]; then
    setup_dir
    FILE=$TMP_DIR/uncomp
    $UNCOMP -c "$1" > $FILE
    FILETYPE=`file "$FILE"`
fi

case "$FILETYPE" in

    *" tar archive")
	setup_dir
	cat "$FILE" | (cd "$TMP_DIR"; tar xf -)
	DVINAME=`tar tf "$FILE" | grep '\.dvi$' | head -1`
	[ -n "$DVINAME" ] || \
	   do_abort "Tar file does not contain a dvi file."
	FILE=$TMP_DIR/$DVINAME
    ;;

esac

"$DIR"xdvi -safer "$FILE"

do_cleanup

exit 0
