#!/bin/sh
# Build the same committed source in two different absolute paths and compare
# the unsigned APKs byte for byte.
set -eu

root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
# shellcheck source=versions
. "$root/versions"
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' 0 1 2 3 15
a="$tmp/a/src"
b="$tmp/a-much-longer-path/b/src"

git -C "$root" diff --quiet
git -C "$root" diff --cached --quiet
status=$(git -C "$root" status --porcelain --untracked-files=normal)
[ -z "$status" ] || {
	echo "verify-repro: tracked and untracked source must be clean" >&2
	exit 1
}

mkdir -p "$a" "$b"
archive="$tmp/source.tar"
git -C "$root" archive --format=tar HEAD > "$archive"
tar -xf "$archive" -C "$a"
tar -xf "$archive" -C "$b"

# Reuse a locally cached, verified source tarball when present. Otherwise the
# first build fetches it and the second consumes that exact verified file.
tarball="rsync/rsync-${RSYNC_VERSION}.tar.gz"
if [ -f "$root/$tarball" ]; then
	( cd "$root/rsync" && sha256sum -c "rsync-${RSYNC_VERSION}.tar.gz.sha256" )
	cp "$root/$tarball" "$a/$tarball"
	cp "$root/$tarball" "$b/$tarball"
fi

make -C "$a" app
if [ ! -f "$b/$tarball" ]; then
	cp "$a/$tarball" "$b/$tarball"
fi
make -C "$b" app

first="$a/app/build/outputs/apk/release/app-release-unsigned.apk"
second="$b/app/build/outputs/apk/release/app-release-unsigned.apk"
if cmp "$first" "$second"; then
	echo "verify-repro: APKs are bit-identical across different paths"
else
	echo "verify-repro: NONDETERMINISM detected" >&2
	exit 1
fi
