#!/bin/sh -efu
#
# When updating a package V1->V2, last changelog entry in V1
# must be present among changelog entries in V2.  This is how
# we can retain NMU and promote QA activity.
#

. gb-sh-functions

fail_if_task_abort_requested

. gb-sh-tmpdir

rc=0
text=OK

changelog()
{
	rpmquery --qf '[%{CHANGELOGTIME}\t%{CHANGELOGNAME}\n]' -p "$1" |
	perl -MPOSIX=strftime -pe 's{\d+}{strftime "%a %b %d %Y", gmtime 86400 * (1 + 2 * int($& / 86400 / 2)) }e' |
	perl -pe 's/\t.*<(\S+)(?:\@| at )([\w-]+).*>[ \t]*/\t$1\@$2\t/'
}

is_git_inherited()
{
	if cmp -s "check-git-inheritance/.$I" "check-git-inheritance/$I"; then
		return 1
	fi
	set_GIT_DIR "$GB_GEARS_DIR" "$1"
	local id
	id="$(git rev-parse --branches="[${GB_REPO_NAME:0:1}]${GB_REPO_NAME:1}" 2>/dev/null)" &&
	[ -n "$id" ]
}

check()
{
	N=$1; shift
	local lastchange

	TZ=UTC changelog "$1" >$tmpdir/c1
	TZ=UTC changelog "$2" >$tmpdir/c2
	lastchange=$(head -1 $tmpdir/c1)
	if fgrep -qs -x -e "${lastchange:?}" $tmpdir/c2; then
		return
	fi

	local lastchangex
	TZ=UTC24 changelog "$1" >$tmpdir/c1x
	lastchangex=$(head -1 $tmpdir/c1x)
	if fgrep -qs -x -e "${lastchangex:?}" $tmpdir/c2; then
		return
	fi
	TZ=UTC-24 changelog "$1" >$tmpdir/c1x
	lastchangex=$(head -1 $tmpdir/c1x)
	if fgrep -qs -x -e "${lastchangex:?}" $tmpdir/c2; then
		return
	fi
	# Last changelog entry generated by kernel-build-tools?
	if echo "${1##*/}" |egrep -qs -x 'kernel-modules-.+\.[0-9]+\.[0-9]+\.src\.rpm'; then
		lastchange=$(head -2 $tmpdir/c1 |tail -1)
		if fgrep -qs -x -e "${lastchange:?}" $tmpdir/c2; then
			return
		fi
	fi
	# Current changelog entry generated by Girar autorelease packager?
	if echo "${2##*/}" |egrep -qs -x '.+\.Build[0-9]+\.src\.rpm'; then
		return
	fi
	echo >&2 "${2##*/}: missing last changelog entry from ${1##*/}:"
	echo >&2 "* $lastchange"

	text=COND-OK
	is_check_failure_tolerated ||
		is_git_inherited "$N" || rc=1
}

join -o 0,1.3,2.4,2.5 plan/{rm,add}-src >$tmpdir/N+F1+P+I
while read -r N F1 P I; do
	F="$GB_REPO_DIR/files/SRPMS/$F1"
	if ! use_repo_files; then
		A=$(printf '%s\n' "$F1" | join -j 1 -o 1.3 plan/add-srpm2arch -)
		F="$GB_REPO_DIR/$A/SRPMS.$GB_REPO_FLAVOUR/$F1"
	fi
	check "$N" "$F" "$P" </dev/null
done <$tmpdir/N+F1+P+I

[ "$rc" = 0 ] || text=FAILED
stamp_echo >&2 "srpm inheritance check $text"
exit $rc
