#!/bin/bash
#
# Invoke whatever HTML viewer is installed...
# Usage:
#	htmlview [URL]
#
# Changes:
# v2.0.0
# ------
# - Allow users to override default settings in
#   ~/.htmlviewrc and /etc/htmlview.conf.
#   Users can define X11BROWSER, TEXTBROWSER and
#   CONSOLE variables to indicate their preferences.
# - --remote and --local are deprecated, we don't
#   have any non-browser HTML viewers these days.
#
# Christopher Blizzard <blizzard@redhat.com> Aug 09 2002 
# - prefer mozilla over galeon
#
# written by Bernhard Rosenkraenzer <bero@redhat.com>
# (c) 2000-2002 Red Hat, Inc.
#
# This script is in the public domain.

exists() {
	local p
	if echo "$1" | grep -q "/"; then
		if [ -x "$1" ]; then
			return 0
		fi
	fi
	for p in `echo $PATH |sed -e "s,:, ,g"`; do
		if [ -x "$p/$1" ]; then
			return 0
		fi
	done
	return 1
}

# ignore legacy cruft
if [ "$1" == "--remote" ]; then
	shift
elif [ "$1" == "--local" ]; then
	shift
fi

unset BROWSER CONSOLE TERMS_KDE TERMS_GNOME TERMS_GENERIC
[ -e /etc/htmlview.conf ] && source /etc/htmlview.conf
[ -e ~/.htmlviewrc ] && source ~/.htmlviewrc

TERMS_KDE="/usr/bin/konsole /usr/bin/kvt"
TERMS_GNOME="/usr/bin/gnome-terminal"
TERMS_GENERIC="/usr/bin/rxvt /usr/X11R6/bin/xterm /usr/bin/Eterm"
TTYBROWSERS="/usr/bin/links /usr/bin/lynx /usr/bin/w3m"
X11BROWSERS_KDE="/usr/bin/konqueror /usr/bin/kfmbrowser"
X11BROWSERS_GNOME="/usr/bin/mozilla /usr/bin/galeon"
X11BROWSERS_GENERIC="/usr/bin/mozilla /usr/bin/netscape"

if [ "x`/sbin/pidof gnome-session`" != "x" ]; then
	GCONF=$(gconftool-2 -g /desktop/gnome/url-handlers/unknown/command \
		2>/dev/null | sed -e 's/%s//')
	X11BROWSERS="$GCONF $X11BROWSERS_GENERIC $X11BROWSERS_GNOME $X11BROWSERS_KDE"
	TERMS="$CONSOLE $TERMS_GENERIC $TERMS_GNOME $TERMS_KDE"
else
	X11BROWSERS="$X11BROWSERS_GENERIC $X11BROWSERS_KDE $X11BROWSERS_GNOME"
	TERMS="$CONSOLE $TERMS_GENERIC $TERMS_KDE $TERMS_GNOME"
fi
[ -n "$X11BROWSER" ] && X11BROWSERS="$X11BROWSER $X11BROWSERS"
[ -n "$TEXTBROWSER" ] && TTYBROWSERS="$TEXTBROWSER $TTYBROWSERS"
[ -n "$CONSOLE" ] && TERMS="$CONSOLE $TERMS"

if test "x$DISPLAY" = x; then
	for i in $TTYBROWSERS; do
		if exists $i; then
			exec $i $*
		fi
	done
	echo $"No valid text mode browser found."
	exit 1
else
	for i in $X11BROWSERS; do
		exists $i && exec $i $*
	done
	for i in $TERMS; do
		if exists $i; then
			CONSOLE="$i -e"
			break
		fi
	done
	for i in $TTYBROWSERS; do
		exists $i && exec $CONSOLE $i $*
	done
	echo $"No valid browser found."
	exit 1
fi

