#!/bin/sh -efu

. gb-sh-functions

fail_if_task_abort_requested

# Check that the plan is consitent with respect to package versioning:
# when replacing packages, versions must increase.

. gb-sh-tmpdir

rc=0

# input: src-N  src-EVR  src-F
# join by src-N
join -t$'\t' -o 1.1,1.2,1.3,2.2,2.3 plan/rm-src plan/add-src >$tmpdir/replace-src
sort -u -o $tmpdir/replace-src{,}

while read -r N EVR1 F1 EVR2 F2; do
	if [ "$F1" = "$F2" ]; then
		echo ' *** new and existing source packages have the same filename'
		printf '%s\t%s\n' "$N" "$F1"
		rc=1
		continue
	fi >&2
	if ! vercheck "$EVR1" "$EVR2"; then
		echo ' *** source package version is either the same or older than existing'
		printf '%s\t%s\t%s\n' "$N" "$EVR1" "$EVR2"
		rc=1
	fi >&2
done <$tmpdir/replace-src

# input: bin-N  bin-EVR  bin-A  bin-F
# join by bin-N
join -t$'\t' -o 1.1,1.2,1.3,1.4,2.2,2.3,2.4 plan/rm-bin plan/add-bin >$tmpdir/replace-bin
sort -u -o $tmpdir/replace-bin{,}

while read -r N EVR1 A1 F1 EVR2 A2 F2; do
	if [ "$F1" = "$F2" ]; then
		echo ' *** new and existing binary packages have the same filename'
		printf '%s\t%s\n' "$N" "$F1"
		rc=1
	fi >&2
	[ "$A1" = "$A2" ] || [ "$A1" = noarch ] || [ "$A2" = noarch ] || continue
	if ! vercheck "$EVR1" "$EVR2"; then
		echo ' *** binary package version is either the same or older than existing'
		printf '%s\t%s\t%s\n' "$N" "$EVR1" "$EVR2"
		rc=1
	fi >&2
done <$tmpdir/replace-bin

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