#!/bin/sh -efu

. gb-sh-functions

fail_if_task_abort_requested

changelog_with_time()
{
	local s='[:space:]'
	local q='[* %{CHANGELOGTIME} %{CHANGELOGTIME:day} %{CHANGELOGNAME}\n%{CHANGELOGTEXT}\n\n]'
	rpmquery --qf "$q" -p "$1" |
	sed -r "s/(<[$s]*[^@>$s]+([$s]*@[$s]*|[$s]+at[$s]+)(packages[$s]*[.][$s]*)?altlinux)([$s]*[.][$s]*|[$s]+dot[$s]+)[[:alpha:]]+[$s]*>/\\1>/"
}

rpm_recent_changes()
{
	changelog_with_time "$1" |
	awk -v time0="$(date -d '3 months ago' +%s)" '
		/^\* [0-9]+ / {
			if ($2 < time0 && printed) exit
			sub(/ [0-9]+ /, " ")
		}
		{ print; printed++ }
	'
}

rpm_changes_since()
{
	local time0 EVR0
	time0=$(rpmquery --qf '%{CHANGELOGTIME}' -p "$2")
	EVR0=$(rpmquery --qf '%|epoch?{%{epoch}:}|%{version}-%{release}' -p "$2")
	changelog_with_time "$1" |
	awk -v time0="$time0" -v EVR0="$EVR0" '
		/^\* [0-9]+ / {
			if ($NF == EVR0) exit
			if ($2 < time0 && printed) exit
			sub(/ [0-9]+ /, " ")
		}
		{ print; printed++ }
	'
}

. gb-sh-tmpdir
join -t$'\t' -o 1.1,1.2,1.3,1.4,1.5,2.3 plan/{add,rm}-src >$tmpdir/src
sort -t$'\t' -u -k1,3 -o $tmpdir/src{,} plan/add-src

# Drop old bugmails if any.
find bugmail -type f -delete

while F0=; read -r N EVR F P I F0; do
	if [ -n "$F0" ]; then
		# Must be executed before commit-repo!
		if use_repo_files; then
			srpm0=$GB_REPO_DIR/files/SRPMS/$F0
		else
			A=$(printf '%s\n' "$F0" | join -j 1 -o 1.2 plan/add-srpm2arch -)
			srpm0=$GB_REPO_DIR/$A/SRPMS.$GB_REPO_FLAVOUR/$F0
		fi
		changelog=$(rpm_changes_since "$P" "$srpm0")
	else
		changelog=$(rpm_recent_changes "$P")
	fi
	ids=$(printf '%s\n' "$changelog" |gb-x-parse-bugs-from-changelog)
	[ -n "$ids" ] || continue
	stamp_echo >&2 "$N: closes bugs: $ids"
	binaries=$(printf '%s\n' "$N" |join -o 2.4 - plan/add-src+bin |sort -u | tr '\n' ' ')
	uploader="$(cat task/owner)"
	for id in $ids; do
		cat >"bugmail/$id" <<-__EOF
		From: ${GB_BUGZILLA_FROM}
		To: ${GB_BUGZILLA_TO}
		X-Bugzilla-In-Bug-Id: ${id}
		X-Bugzilla-In-Source-Package: ${N}
		X-Bugzilla-In-Binary-Packages: ${binaries}
		X-Bugzilla-In-Uploader: ${uploader}

		@bug_id=${id}
		@bug_status=RESOLVED
		@resolution=FIXED

		${N}-${EVR} -> $GB_REPO_NAME:

		${changelog}
		__EOF
	done
done <$tmpdir/src
