#!/bin/sh
#
# This script tests whether sbuild can work with a very minimal chroot (only
# build-essential and apt), whether unshare mode works and whether signing
# works.
#
# After bugs #977674 and #981021 are fixed, also test --source-only-changes

set -exu

if [ -z ${AUTOPKGTEST_TMP+x} ]; then
	echo "AUTOPKGTEST_TMP is unset" >&2
	exit 1
fi

release=$(./debian/tests/get_default_release.py)
if [ -z "$release" ]; then
	echo "cannot get default release" >&2
	exit 1
fi
nativearch=$(dpkg --print-architecture)
# only run the cross-tests on amd64 crossing for arm64 as per
# https://lists.debian.org/msgid-search/173156754864.3649146.10791472176546387428@localhost
foreignarch=
if [ "$nativearch" = amd64 ]; then
	foreignarch=arm64
fi

mkdir -p "${AUTOPKGTEST_TMP}/gpghome"
chmod 700 "${AUTOPKGTEST_TMP}/gpghome"
export GNUPGHOME="${AUTOPKGTEST_TMP}/gpghome"

verify_orig() {
	echo "verifying test-pkg_1.0.tar.xz" >&2
	cat << END | base64 -d | xz -cd > "${AUTOPKGTEST_TMP}/expected"
/Td6WFoAAATm1rRGAgAhARwAAAAQz1jM4Cf/BCJdADoZSs4dfiUjFYSOxzYxnd+/m6AlVEVOGf2j
nT6NK0F9XZ7LLydbY3I//WjMOM2RFpGUqZ8R8Q8lLmydB5SLN5ZQSPW3OJjHlzxVQmv2v3KUyPxo
V5uvr2rp1j0gfmjB4O+m6SMxUWGmCOp3mrA13iUy99dt9OK9tRQagXItob106li/2LWmOsXR3/5M
8m/JLF/6KIaYolPsvzut8mTFmik8s22eXjugZufC7CQwXJ7KVb8/LPYgLzHo8tKwkrieBonYFwD+
R17Q1wsK/wbdQCw78oh4JrairZPz0NY1WsY/6GXQZOeo0Wl3dgG0PmrQtgPH133asZz5XgrtfDwU
KqaSBmKWIGrht7IqByDr5Bf+XyzpU9vwiE30hIVmvzCQDnNIrcaO5wZJQgujJreb4k1BKKmZJ4dT
B46ae4yTd8zLLGH7YwFWk145SHCQJOBakSuVGjej3zElgoNsTwYTAK5J3wQX/BEszByCX+5AKUP3
v4ZG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OPKGTEST_TMP}/expected" "${AUTOPKGTEST_TMP}/test-pkg_1.0.tar"
	rm "${AUTOPKGTEST_TMP}/expected" "${AUTOPKGTEST_TMP}/test-pkg_1.0.tar"
}

verify_deb() {
	echo "verifying test-pkg_1.0_all.deb" >&2
	data_tar=$(ar t "${AUTOPKGTEST_TMP}/test-pkg_1.0_all.deb" | grep "^data\.tar\.")
	case "$data_tar" in
		data.tar.xz)
			cat << END | base64 -d > "${AUTOPKGTEST_TMP}/expected"
ITxhcmNoPgpkZWJpYW4tYmluYXJ5ICAgMTQ2NzMxMDUxMiAgMCAgICAgMCAgICAgMTAwNjQ0ICA0
ICAgICAgICAgYAoyLjAKY29udHJvbC50YXIueHogIDE0NjczMTA1MTIgIDAgICAgIDAgICAgIDEw
MDY0NCAgNDYwICAgICAgIGAK/Td6WFoAAATm1rRGBMCLA4BQIQEWAAAAAAAAABDCPtjgJ/8Bg10A
Fwu8HH0BlcAdSj55FcLMJqNUbvT+gy5sC9KUdfhWlMfx+HFB6yCe/fISQhBljyagwzHK2z0fjzyl
9Q5RM24IJQO/ldGzSmZVQWpU6KVdaPbRDHZuPdcqnL6anvCMgysm5qSPjjXVOwMVwj6jVZ5T2sCV
Fd/tSdNnW1XFUQn9644MqVzknw4SL9DaLW7i3+zDmOmKLa1uyfXLuKVwGKiN/XsSDaT3B5SeuLIF
zwuAJSCguYhU4uMPUxWJnyNUaQwmnOO3Xd+TOkvIqqSrdnOHGqbp12kRpSDYAwHfpmldwagZ/ASu
HwJhd7Lk9pL1pNzWZazJ9RoCkHx449h6+exGzkVLLw7R+Exmp1O27wZC9/RuDyQE0JOY4Y1jGp1A
fH5U9xynjVoRrP5/hETw+GrGZoDShN8D/Z7rG5ICtTEqnspW6LWJLCDwndpz6OplHPZTDKckJYp7
U6sXoF5ISdBIUEAc7XBEN61AQTJnfZ6L8d4L87WDLz5bFzwsk3o7cl5PzAXsAAAwfo4j+rTojAAB
pwOAUAAA0BcJAbHEZ/sCAAAAAARZWmRh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ICAgICAgYAootS/9ZAAnDQIA0sIJEMCnA7Qs/x3bV/QmIfh6
PwWjUsxVhqCTvrqW2V7Eot1IE/e77AEECSCQmwfPBhwGBrB/kHoYkACmAPOJugHP3myvCg==
END
			;;
		*)
			echo "Unrecognized deb data archive format" >&2
			return 1
			;;
	esac
	diffoscope "${AUTOPKGTEST_TMP}/expected" "${AUTOPKGTEST_TMP}/test-pkg_1.0_all.deb"
	rm "${AUTOPKGTEST_TMP}/expected"
}

verify_dsc() {
	# we shouldn't have to manually pass the keyring because the path is an
	# implementation detail of gnupg (it used to be named pubring.gpg in
	# the past) but dscverify ignores GNUPGHOME, see Debian bug #981008
	echo "verifying test-pkg_1.0.dsc" >&2
	dscverify --keyring="${AUTOPKGTEST_TMP}/gpghome/pubring.kbx" \
		"${AUTOPKGTEST_TMP}/test-pkg_1.0.dsc"
}

verify_bin_changes() {
	echo "verifying test-pkg_1.0_${nativearch}.changes" >&2
	dscverify --keyring="${AUTOPKGTEST_TMP}/gpghome/pubring.kbx" \
		"${AUTOPKGTEST_TMP}/test-pkg_1.0_${nativearch}.changes"
}

verify_foreign_bin_changes() {
	echo "verifying test-pkg_1.0_${foreignarch}.changes" >&2
	dscverify --keyring="${AUTOPKGTEST_TMP}/gpghome/pubring.kbx" \
		"${AUTOPKGTEST_TMP}/test-pkg_1.0_${foreignarch}.changes"
}

verify_src_changes() {
	echo "verifying test-pkg_1.0_source.changes" >&2
	dscverify --keyring="${AUTOPKGTEST_TMP}/gpghome/pubring.kbx" \
		"${AUTOPKGTEST_TMP}/test-pkg_1.0_source.changes"
}

verify_commands_log() {
	echo "verifying absolute path in --pre-build-commands" >&2
	! grep -v / "${AUTOPKGTEST_TMP}/pre-build-commands.log"
}

verify() {
	for thing in "$@"; do
		"verify_$thing"
	done
	# remove verified files, so that we make sure not to accidentally
	# verify anything from an earlier build
	rm "${AUTOPKGTEST_TMP}/test-pkg_1.0_all.deb" \
		"${AUTOPKGTEST_TMP}/test-pkg_1.0.tar.xz" \
		"${AUTOPKGTEST_TMP}/test-pkg_1.0.dsc"
	rm -f "${AUTOPKGTEST_TMP}/test-pkg_1.0_${nativearch}.changes" \
		"${AUTOPKGTEST_TMP}/test-pkg_1.0_source.changes" \
		"${AUTOPKGTEST_TMP}/test-pkg_1.0_${nativearch}.buildinfo" \
		"${AUTOPKGTEST_TMP}/test-pkg_1.0_source.buildinfo" \
		"${AUTOPKGTEST_TMP}/pre-build-commands.log"
}

sqop generate-key "sbuild fake uploader <fake-uploader@debian.org>" > "${AUTOPKGTEST_TMP}/key.asc"
gpg --batch --allow-secret-key-import --import - < "${AUTOPKGTEST_TMP}/key.asc"

# Ensure umask is consistent with the blobs above; Debian is already 022 but
# Ubuntu defaults to 002
umask 022
mkdir -p "${AUTOPKGTEST_TMP}/test-pkg-1.0/debian/source"

cat << END > "${AUTOPKGTEST_TMP}/test-pkg-1.0/debian/control"
Source: test-pkg
Section: debug
Priority: optional
Maintainer: sbuild maintainers <sbuild@packages.debian.org>
Uploaders: sbuild fake uploader <fake-uploader@debian.org>
Standards-Version: 4.5.1

Package: test-pkg
Architecture: all
Description: test package
 This is a test package for debugging purposes, with a fake description
 to cheat linters into believing this contains some actual valuable text
 that the reader can make some sense of.
END

cat << END > "${AUTOPKGTEST_TMP}/test-pkg-1.0/debian/changelog"
test-pkg (1.0) unstable; urgency=low

  * Entry. Closes: #12345

 -- sbuild fake uploader <fake-uploader@debian.org>  Thu, 30 Jun 2016 20:15:12 +0200
END

cat << END > "${AUTOPKGTEST_TMP}/test-pkg-1.0/debian/copyright"
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/

Files: *
Copyright:
 Copyright © 2021 sbuild maintainers <sbuild@packages.debian.org>
License: GPL-2+
 This program is free software; you can redistribute it and/or modify it under
 the terms of the GNU General Public License as published by the Free Software
 Foundation; either version 2 of the License, or (at your option) any later
 version.
 .
 On Debian systems, the full text of the GNU General Public License version 2
 can be found in the file /usr/share/common-licenses/GPL-2.
END

cat << END > "${AUTOPKGTEST_TMP}/test-pkg-1.0/debian/rules"
#!/usr/bin/make -f

clean:
	rm -rf debian/files debian/tmp

build-indep:
build-arch:
build: build-indep build-arch

binary-indep: build-indep
	rm -rf debian/tmp
	mkdir -p debian/tmp/DEBIAN
	dpkg-gencontrol
	dpkg-deb --root-owner-group --build debian/tmp ..

binary-arch: build-arch

binary: binary-indep binary-arch

.PHONY: clean build-indep build-arch build binary-indexp binary-arch binary
END
chmod +x "${AUTOPKGTEST_TMP}/test-pkg-1.0/debian/rules"

cat << END > "${AUTOPKGTEST_TMP}/test-pkg-1.0/debian/source/format"
3.0 (native)
END

if ! mmdebstrap --mode=unshare --variant=apt \
	--include=ca-certificates \
	--architecture="$nativearch,$foreignarch" \
	--debug \
	--hook-dir=/usr/share/mmdebstrap/hooks/copy-host-apt-sources-and-preferences \
	--hook-dir=/usr/share/mmdebstrap/hooks/file-mirror-automount \
	--skip=cleanup/apt/lists \
	"" \
	"${AUTOPKGTEST_TMP}/chroot.tar"; then
	echo "Creating chroot with mmdebstrap failed: cannot continue test" >&2
	exit 77
fi

env --chdir="${AUTOPKGTEST_TMP}/test-pkg-1.0/" dpkg-buildpackage --sign-keyfile="${AUTOPKGTEST_TMP}/key.asc" --build=full
env --chdir="${AUTOPKGTEST_TMP}/test-pkg-1.0/" dpkg-buildpackage --sign-keyfile="${AUTOPKGTEST_TMP}/key.asc" --target=clean
verify orig deb dsc bin_changes

run_sbuild() {
	workingdir=$1
	shift
	env --chdir="${AUTOPKGTEST_TMP}/$workingdir/" sbuild \
		--no-source-only-changes --nolog \
		--bd-uninstallable-explainer=apt \
		--chroot="${AUTOPKGTEST_TMP}/chroot.tar" --chroot-mode=unshare \
		--keyid="sbuild fake uploader <fake-uploader@debian.org>" \
		--pre-build-commands="echo %SBUILD_DSC > ${AUTOPKGTEST_TMP}/pre-build-commands.log" \
		--no-run-lintian --no-run-autopkgtest \
		--no-apt-upgrade --no-apt-distupgrade --no-apt-update \
		"$@"
}

# Test running sbuild from the unpacked source
run_sbuild test-pkg-1.0 --source
verify orig deb dsc bin_changes commands_log

run_sbuild test-pkg-1.0
verify orig deb bin_changes commands_log

# disable cross-builds until #1088971 is fixed in autopkgtest
if false; then
	if [ "$nativearch" = amd64 ]; then
		run_sbuild test-pkg-1.0 --build="$nativearch" --host="$foreignarch" --arch-all
		verify orig deb foreign_bin_changes
	fi
fi

# Test running sbuild on the dsc
env --chdir="${AUTOPKGTEST_TMP}/test-pkg-1.0/" dpkg-source --build .
run_sbuild '' --source -d "$release" test-pkg_1.0.dsc
verify orig deb dsc bin_changes commands_log

env --chdir="${AUTOPKGTEST_TMP}/test-pkg-1.0/" dpkg-source --build .
run_sbuild '' -d "$release" test-pkg_1.0.dsc
verify orig deb bin_changes commands_log

# Test symlinked .dsc (see https://bugs.debian.org/1012856)
env --chdir="${AUTOPKGTEST_TMP}/test-pkg-1.0/" dpkg-source --build .
mv "${AUTOPKGTEST_TMP}/test-pkg_1.0.dsc" "${AUTOPKGTEST_TMP}/test-pkg_1.0_symlink.txt"
ln -s test-pkg_1.0_symlink.txt "${AUTOPKGTEST_TMP}/test-pkg_1.0.dsc"
run_sbuild '' -d "$release" test-pkg_1.0.dsc
verify orig deb bin_changes commands_log

gpgconf --kill all || :
rm -r -- "${AUTOPKGTEST_TMP}/gpghome/" "${AUTOPKGTEST_TMP}/key.asc"
rm "${AUTOPKGTEST_TMP}/test-pkg-1.0/debian/changelog" \
	"${AUTOPKGTEST_TMP}/test-pkg-1.0/debian/control" \
	"${AUTOPKGTEST_TMP}/test-pkg-1.0/debian/source/format" \
	"${AUTOPKGTEST_TMP}/test-pkg-1.0/debian/rules" \
	"${AUTOPKGTEST_TMP}/test-pkg-1.0/debian/copyright"
rmdir "${AUTOPKGTEST_TMP}/test-pkg-1.0/debian/source" \
	"${AUTOPKGTEST_TMP}/test-pkg-1.0/debian" \
	"${AUTOPKGTEST_TMP}/test-pkg-1.0"
rm "${AUTOPKGTEST_TMP}/chroot.tar"
