#!/bin/sh -ef
export LC_ALL=C

bugzilla="${1-https://bugzilla.altlinux.org}"
columns="bug_id,component,bug_severity,bug_status,resolution,short_desc"
URL="$bugzilla/buglist.cgi?ctype=csv&columnlist=$columns"

csv2tab()
{
	perl -Mstrict -le \
'	use FileHandle;
	use Text::CSV_XS;
	our $CSV ||= new Text::CSV_XS { binary => 1 };
	while (my $ary = $CSV->getline(\*STDIN)) {
		last if @$ary == 0 and eof;
		s/[[:cntrl:]]+/ /g for @$ary;
		print join "\t", map { $_ || "x" } @$ary[0..5]; # 6 fields
	}
'
}

dump()
{
	cd "${workdir:?}"
	wget --non-verbose --tries=1 --timeout=60 -O wget.out "$URL" &>wget.sucks ||
		{ echo "wget sucks:"; cat wget.sucks; return 1; } >&2
	sed 1d wget.out |csv2tab
	cd -
}

dump

noun=bug
opt_join=1

filter()
{
	awk -F'\t' "{if ($1) print; else print >\"/dev/fd/3\"}
	function resolved(status,resolution) {
		return (status ~/CLOSED|RESOLVED/ &&
		resolution ~/FIXED|INVALID|WONTFIX|WORKSFORME|DUPLICATE/) }"
}

fmt_new()
{
	filter 'resolved($4,$5)' >new-resolved.bugs 3>new.bugs
	if [ -s new-resolved.bugs ]; then
		n=`wc -l <new-resolved.bugs`
		subj="$subj +$n!"
		echo "	$n NEW $(count "$n" "$noun") quickly RESOLVED"; echo
		awk -F'\t' '{printf "#%s\t%-16s\t%-8s\t%s\n%s\n\n", $1, $2, $3, $5, $6}' <new-resolved.bugs
	fi
	if [ -s new.bugs ]; then
		n=`wc -l <new.bugs`
		subj="$subj +$n"
		echo "	$n NEW $(count "$n" "$noun")"; echo
		awk -F'\t' '{printf "#%s\t%-16s\t%s\n%s\n\n", $1, $2, $3, $6}' <new.bugs
	fi
}

fmt_old()
{
	echo "	$1 OLD $2 unexpectedly removed from the database"; echo
	awk -F'\t' '{printf "#%s\t%-16s\t%-8s\t%-8s\t%s\n%s\n\n", $1, $2, $3, $4, $5, $6}'
}

#	1	2	3	4	5	6	7	8	9	10	11
#	bug_id	compon1	severi1	status1	resolu1	descri1	compon2	severi2	status2	resolu2	descri2
fmt_updated()
{
	filter '!resolved($4,$5)&&resolved($9,$10)' >resolved.bugs 3>/dev/null
	[ -s resolved.bugs ] || return 0
	local n=`wc -l <resolved.bugs`
	subj="$subj -$n"
	echo "	$n RESOLVED $(count "$n" "$noun")"; echo
	awk -F'\t' '{printf "#%s\t%-16s\t%-8s\t%s\n%s\n\n", $1, $7, $8, $10, $11}' <resolved.bugs
}

fmt_total()
{
	filter '!resolved($4,$5)' >pending.bugs 3>/dev/null
	local n=`wc -l <pending.bugs`
	subj="$subj ($n)"
	echo "Total $n pending bugs."
}
