#!/bin/sh -e

# X11 application wrapper for metamail
# (c) 1994 Roman Czyborra

# Applications which open their own output windows do not need stdio
# for interaction. So why should we sit and block the mail reader?

# Close unused file descriptor so Emacs or Netscape won't wait for it.

if [ ! -t 2 ]; then exec 2>/dev/null; fi

# Parse arguments.

suffix=; case "$1" in .*) suffix="$1"; shift; esac

case "$1" in
 */*)	S="$IFS"; IFS=/; for viewer in $1; do : ; done; IFS="$S";;
  -t)	shift && viewer=view;;
  ?*)	viewer="$1";;
   *)	echo 'Usage: xviewer [ .suffix ] [ -t ] viewer [ -options ] < file'
	exit 1
esac

# What if we don't see our favorite display?

case "$viewer,$DISPLAY" in 
xdu,)	exec ${PAGER-less} ;;
emacs,|xmaplay,) viewer=view;;
xplay,|soundtool,|audiotool,) exec gzip -dcf > /dev/audio;;
xterm,)	while shift && [ -e != "$1" ]; do :; done; shift; viewer=view;;
xdvi,)	suffix=.dvi; viewer=view; set ${DVI2TTY-/usr/TeX/bin/dvi2tty};;
view,*)	if [ "$MM_NOTTTY" != 1 ] && [ -t 0 -a -t 1 ] < /dev/tty
	then :
	elif [ -n "$DISPLAY" ]
	then viewer=xterm && set xterm -e "$@"
	else exec cat
	fi;;
*:*)	case "$MM_QUIET" in 1|*xviewer*) ;; ?*)
	echo "   Okay, a new $viewer window shall pop up."
	esac;;
*)	echo "$viewer can only be run it the X11 window system!"
	exec cat > /dev/null;;
esac

# xv doesn't need a tempfile, it stores the entire picture in its own
# memory and offers to save it to a file.

case "$viewer" in xv)
	exec perl -we 'undef $/; $image = <STDIN>; fork && exit;
		open (XV, "|-") || exec @ARGV; print XV $image;' "$@" -;;

# cxterm needs some additional setup

cxterm)	export HZINPUTDIR XENVIRONMENT
	: ${HZINPUTDIR=/usr/X11/lib/cxterm.dic}
	: ${XENVIRONMENT=/usr/X11/lib/app-defaults/CXterm}
esac

# For all others, save the data to a temporary file which will be
# removed after the show.

tmpfile="${TMPDIR-/tmp}/$viewer$$@${HOST-localhost}$suffix"
trap 'exec rm -f "$tmpfile"' 0 1 2 3 15; umask 77

# Some Web browsers ignore compression labels.

case "$LYNX_VERSION" in
2*)		gzip -dcf > "$tmpfile";;
*)		cat > "$tmpfile"
esac

# Finally launch the viewer

case "$viewer" in
view)	"${@-${PAGER-less}}" "$tmpfile" < /dev/tty;;
*)	(trap 'exec rm -f "$tmpfile"' 0 2 3 15; trap "" 1
	PATH="$PATH:/usr/X11/bin:/usr/TeX/bin:/usr/www/bin:/usr/openwin/bin" \
	"$@" "$tmpfile"
	rm "$tmpfile") >/dev/null & kill -CONT $! && trap "" 0
esac
