#!/bin/sh
#
# Generates a bug report
#
# Christoph Lameter, October 26, 1996
#
set -e

if [ "$1" = "" ]; then
	echo "Usage: bug <packagename> [<text>] .."
	exit 1
fi

PACKAGE=$1

shift

if [ "$VISUAL" = "" ]; then
	VISUAL="$EDITOR"
	if [ "$VISUAL" = "" ]; then
		VISUAL="joe"
	fi
fi

function checkconf()
{ 
# Takes two parameters filename and md5sum and checks if the file was modified
# If so outputs the filename
	if [ -r $1 ]; then
		SUM=`md5sum $1`
		SUM=`expr "$SUM" : '\(.*\) .*'`
		if [ "$SUM" != "$2" ]; then
			echo "$1"
		fi
	else
		echo $1
	fi
}

function checkconfs()
{
	read X
	while [ "$X" ]; do
		if [ `expr match "$X" ".*:"` = 0 ]; then
			checkconf $X
		fi
		if ! read X ; then
			return
		fi
	done
}

if [ -f /var/lib/dpkg/info/$PACKAGE.list ]; then
	dpkg -s $PACKAGE >/tmp/$$
	VERSION=`grep Version: /tmp/$$`
	DEPS=`grep Depends: /tmp/$$` || DEPS=""
	if grep -q "Conffiles:" /tmp/$$; then
		MODCONF=`sed -n </tmp/$$  -e '/Conffiles:/,/Description:/p'|checkconfs`
	fi
	cat >/tmp/$$ <<EOF
Package: $PACKAGE
$VERSION

-- Please describe the problems with the package here

$*

-- System Information
Debian Release: `cat /etc/debian_version`
Kernel Version: `uname -a`

EOF

	if [ "$DEPS" != "" ]; then
		echo "Versions of the packages this package depends on:" >>/tmp/$$
		DEPS=`echo "$DEPS"|tr ",\n" "  "|sed -e "s/ (.*)//g" -e "s/Pre-Depends://g" -e "s/Depends://g" `	
		for i in $DEPS; do
			if [ -f /var/lib/dpkg/info/$i.list ]; then
				echo "$i	`dpkg -s $i|grep 'Version:'`" >>/tmp/$$
			else
				echo "$i	Not installed or no info" >>/tmp/$$
			fi
		done
	fi

	if [ "$MODCONF" != "" ]; then
		for i in $MODCONF; do
			echo -e "\n--- Begin $i (modified conffile)" >>/tmp/$$
			if [ -r $i ]; then
				sed -e '/^#/d' -e '/^$/d' <$i >>/tmp/$$
			else
				echo "Config file not present or no permissions for access" >>/tmp/$$
			fi
			echo "--- End $i" >>/tmp/$$
		done
	fi

	echo -e "\n-- bug report generated by the debmake bug tool" >>/tmp/$$
	if [ "$1" = "" ]; then
		cp /tmp/$$ /tmp/$$backup
		$VISUAL +6 /tmp/$$
		if [ $? ]; then
			if cmp /tmp/$$ /tmp/$$backup >/dev/null; then
				echo "No changes: No Bug report send"
				rm /tmp/$$ /tmp/$$backup
				exit 1;
			fi
		else
			echo "Editor Aborted: No Bug report send"
			rm /tmp/$$ /tmp/$$backup
			exit 1;
		fi
		rm /tmp/$$backup
	fi
#	mail postmaster -s "Bug in $PACKAGE $VERSION" </tmp/$$
	mail submit@bugs.debian.org -s "Bug in $PACKAGE $VERSION" </tmp/$$
	rm /tmp/$$
else
	echo "Package $PACKAGE not installed"
fi
