#!/usr/bin/env bash
set -Eeuo pipefail

suite='stretch'
timestamp='2017-01-01T00:00:00Z'

expectedEpoch='1483228800'
expectedSha256='26490ed3400a5029b8b5939c6cebd38691e28ea5c616bb54f25f758125417c5f'

tempDir="$(mktemp -d)"
trap "rm -rf '$tempDir'" EXIT
rootfs="$tempDir/rootfs"

set -x

debuerreotype-init "$rootfs" "$suite" "$timestamp"
[ "$(< "$rootfs/debuerreotype-epoch")" = "$expectedEpoch" ]

debuerreotype-chroot "$rootfs" true

debuerreotype-debian-sources-list "$rootfs" "$suite"
# remove effect of https://github.com/debuerreotype/debuerreotype/pull/56 (to avoid regenerating expected tarballs to compensate)
sed -i -e '/^#/d' "$rootfs/etc/apt/sources.list"

debuerreotype-tar "$rootfs" "$tempDir/actual.tar"
sha256="$(sha256sum "$tempDir/actual.tar" | cut -d' ' -f1)"

# see https://people.debian.org/~tianon/debuerreotype/

if [ "$sha256" != "$expectedSha256" ]; then
	(
		set +x
		echo >&2
		echo >&2 'ERROR: expected SHA256 does not match actual -- downloading pristine source to compare (via diffoscope)'
		echo >&2
	)

	toCompare="https://people.debian.org/~tianon/debuerreotype/$suite--$timestamp--$expectedSha256.txz"
	wget -qO "$tempDir/expected.txz" "$toCompare"
	xz -d < "$tempDir/expected.txz" > "$tempDir/expected.tar"
	diffoscope >&2 "$tempDir/expected.tar" "$tempDir/actual.tar"
	exit 1
fi
