#!/bin/sh

set -x
set -e

TESTREPO=$1
SVNWORKDIR=$2
if [ -z "${TESTREPO}" ]; then
	echo "Specify the local / private test root URL."
	exit 800
fi
SANITY=`echo ${TESTREPO} | grep svn.debian || true`
if [ -n "$SANITY" ]; then
	echo "Please use a local repo, not a Debian one!"
	exit 900
fi
SANITY=`echo ${TESTREPO} | grep svn.alioth || true`
if [ -n "$SANITY" ]; then
	echo "Please use a local repo, not an Alioth one!"
	exit 1000
fi
echo "Checking the local test package version:"
dch -i "svn-buildpackage test suite: test 1" -D unstable
debcommit
VERSION=`parsechangelog |grep Version:|cut -d' ' -f2`
svn-buildpackage -uc -us --svn-tag --svn-noautodch
CHECK=`svn cat ${TESTREPO}/tags/${VERSION}/debian/changelog |head -n1|sed -e 's/.*(\(.*\)).*/\1/'`
if [ "$VERSION" != "$CHECK" ]; then
	set +x
	echo "ERROR 1: parsechangelog fails to match tag changelog"
	INST=`dpkg-query -W -f='${Version}' svn-buildpackage`
	echo "Tested svn-buildpackage (${INST})"
	if [ -n "${SVNWORKDIR}" -a -d ${SVNWORKDIR} ]; then
		set -x
		WORKING=`cat ${SVNWORKDIR}/debian/changelog |head -n1|sed -e 's/.*(\(.*\)).*/\1/'`
		echo "Testing svn-buildpackage (${WORKING}) from ${SVNWORKDIR}"
		dch -i "svn-buildpackage test suite: test 1: working copy ${WORKING}" -D unstable
		debcommit
		VERSION=`parsechangelog |grep Version:|cut -d' ' -f2`
		SVNBPPERLLIB=${SVNWORKDIR} ${SVNWORKDIR}/svn-buildpackage -uc -us --svn-tag --svn-noautodch
		CHECK=`svn cat ${TESTREPO}/tags/${VERSION}/debian/changelog |head -n1|sed -e 's/.*(\(.*\)).*/\1/'`
		if [ "$VERSION" != "$CHECK" ]; then
			set +x
			echo "ERROR 1: parsechangelog fails to match tag changelog"
			exit 2
		else
			echo "SUCCESS @ test 1 for ${WORKING} in ${SVNWORKDIR}"
		fi
	fi
	echo "Fail for svn-buildpackage (${INST})"
	exit 1
else
	echo "SUCCESS @ test 1"
fi
