#! /bin/bash
# bugview -- display debian bugs
#
#Author:	Adam Di Carlo <aph@debian.org>
#Copyright:	GPL v2
#Version:	3.3.10.1
#
#Bugs:
#	view by maintainer name?

set -e

export TEXTDOMAIN=bug
running=nop

if [ -z "$X11BROWSER" -a -n "$DISPLAY" ]; then

	POSIBLE="mozilla konqueror netscape amaya arena"

	RUNNING=$(xlsclients |
		cut -d " " -f3 |
		egrep $(echo $POSIBLE |
		sed -e 's/mozilla\>/mozilla-bin/g' -e 's/ /|/g') |
		head -1 |
		sed -e 's|/mozilla-bin$|/mozilla|'
		)

	if [ "$RUNNING" -a -x "$RUNNING" ]; then
		X11BROWSER="$RUNNING"
		running=yep
	else

		for i in $POSIBLE ; do
			if type "$i" &> /dev/null ; then
				X11BROWSER="$i"
				break
			fi
		done
	fi
fi

CONSOLEBROWSER="${CONSOLEBROWSER:-lynx}"
#BUGSERVER=http://bugs.debian.org/%s
BUGSERVER=http://bugs.debian.org/cgi-bin/pkgreport.cgi?pkg=%s


# source our config file
[ -f /etc/bugview.conf ] && source /etc/bugview.conf

me=$(basename $0)

is_int() { expr "$1" : '[0-9][0-9]*$' > /dev/null; }

if is_int "$1" ; then
	BUGSERVER='http://bugs.debian.org/cgi-bin/bugreport.cgi?archive=no&bug=%s'
fi

encode_url()
{
	local -i i=0
	local s=$1
	local n=${#s}
	local r=""
	while [ $i -lt $n ]; do
		l=${s:$i:1}

		case $l in
			+|=|%)
				l=%$(echo -n $l | od -tx1 | head -1 | cut -d " " -f2)
				;;
		esac

		r="${r}${l}"

		i=$(( $i + 1 ))
	done
	echo $r
}

usage () {
echo $"Usage:  bugview <bug>
View bugs from the Debian BTS on the web.  <bug> can be either 
a package name or a bug number."
echo
echo -n $"The default X11 browser is "
echo "\`$X11BROWSER';"
echo -n $"the default console browser is "
echo "\`$CONSOLEBROWSER'."
echo $"You can override these defaults by setting
X11BROWSER and CONSOLEBROWSER, respectively."
}

while getopts h? opt; do
	case "$opt" in
		h|?)	usage
			exit;;
		*)	echo "Invalid argument: $opt" 1>&2
			usage 1>&2
			exit 1;;
	esac
done

shift `expr $OPTIND - 1`

if [ "$#" -ne 1 ]; then
    usage 1>&2
    exit 1
fi

uid=$(id -u)

if [ "$DISPLAY" ] && command -v "$X11BROWSER" &>/dev/null; then
    BROWSER="$X11BROWSER"
else
    BROWSER="$CONSOLEBROWSER"
fi

# netscape wrapper won't allow being ran by root
if [ $BROWSER = netscape -a $uid -eq 0 ]; then
	BROWSER="$CONSOLEBROWSER"
fi

URL=$(printf "$BUGSERVER" $(encode_url "$1" ) )

# If we know $BROWSER is an X11 browser, we send it to the background
if echo $(basename $BROWSER) | egrep -q 'netscape|mozilla|amaya|arena|mosaic|opera' ; then
	case $BROWSER in
		*mozilla|*netscape)
			if [ $running = yep ]; then
				"$BROWSER" -remote openURL\("$URL"\)
			else
				"$BROWSER" "$URL" &
			fi
			;;
		*)
			"$BROWSER" "$URL" &
	esac
else
	exec "$BROWSER" "$URL"
fi
