#!/bin/bash
# B92_diffoscope: run diffoscope if needed
#
# We run this hook from the chroot as we can install the version
# of diffoscope that matches our build environment; and get the latest
# improvements if it's unstable.

print_reproducible() {
	echo
	echo "                              _            _ _     _      "
	echo " _ __ ___ _ __  _ __ ___   __| |_   _  ___(_) |__ | | ___ "
	echo "| '__/ _ \ '_ \| '__/ _ \ / _\` | | | |/ __| | '_ \| |/ _ \\"
	echo "| | |  __/ |_) | | | (_) | (_| | |_| | (__| | |_) | |  __/"
	echo "|_|  \___| .__/|_|  \___/ \__,_|\__,_|\___|_|_.__/|_|\___|"
	echo "         |_|                                              "
	echo
}

# cope with pbuilder < 0.216
BUILDDIR=${BUILDDIR:-/tmp/buildd}

echo "I: BUILDDIR is $BUILDDIR"

[ -f $BUILDDIR/initial_build.tar ] || exit 0

echo "I: unpacking initial build material"
mkdir -p /tmp/initial_build
tar -C /tmp/initial_build -xf $BUILDDIR/initial_build.tar
rm $BUILDDIR/initial_build.tar

# Remove .buildinfo files from .changes, as they are not identical
sed -i -e '/^ [a-f0-9]\{32,64\} .*\.buildinfo$/d' /tmp/initial_build/*.changes $BUILDDIR/*.changes

echo "I: comparing build artefacts with cmp"
[ -x /usr/bin/dcmd ] || apt-get install -y --no-install-recommends devscripts 2>&1 > /dev/null
FILES1=$(dcmd find /tmp/initial_build/*.changes -exec basename '{}' \; | LC_ALL=C sort)
FILES2=$(dcmd find $BUILDDIR/*.changes -exec basename '{}' \; | LC_ALL=C sort)
if [ "$FILES1" = "$FILES2" ]; then
	DIFF=0
	for file in $FILES1;
	do
		cmp -s "/tmp/initial_build/$file" "$BUILDDIR/$file"
		DIFF=$?
		[ $DIFF -gt 0 ] && break
	done
	if [ $DIFF -eq 0 ]; then
		print_reproducible
		echo "D: skipping installing and running diffoscope as package is reproducible"
		exit 0
	fi
fi


echo "I: installing diffoscope..."
apt-get install -y --install-recommends sudo diffoscope 2>&1 > /dev/null
touch $BUILDDIR/diffoscope.{txt,html}
chown nobody $BUILDDIR/diffoscope.{txt,html}
echo "I: running it on the package..."
if sudo -u nobody diffoscope --text $BUILDDIR/diffoscope.txt --html $BUILDDIR/diffoscope.html /tmp/initial_build/*.changes $BUILDDIR/*.changes; then
	print_reproducible
	rm -f $BUILDDIR/diffoscope.{txt,html}
fi
