#!/bin/sh
#
# This script ensures that a software distribution will actually work.
# The idea is inspired by 'make distcheck' in GNU Automake:
# https://www.gnu.org/software/automake/manual/html_node/Checking-the-Distribution.html

set -ue

: "${1:?release tarball}"

compiler=
strict=yes
ut_san=
generator=

usage() {
	echo "Usage: $(basename "$0") [-cGSs] tarball"
	echo " -c compiler     Specify C compiler"
	echo " -G generator    Specify Cmake generator"
	echo " -S              Disable strict build (-Werror)"
	echo " -s              Enable unit test sanitizers"
	exit 1
} >&2

while getopts c:G:hSs opt; do
    case "$opt" in
	c) compiler="$OPTARG";;
	G) generator="$OPTARG";;
	S) strict="";;
	s) ut_san="yes";;
	*) usage;;
	esac
done
shift $((OPTIND - 1))

abspath() (
	cd "${1%/*}"
	echo "$PWD/${1##*/}"
)

tarball="$(abspath "${1:?tarball}")"

tempdir="$(mktemp -d)"
atexit() {
	ex="$?"
	rm -rf "$tempdir"
	case "$ex" in
	0)  echo >&2 "OK.";;
	*)  echo >&2 "FAIL.";;
	esac
    exit "$ex"
}
trap atexit EXIT
cd "$tempdir"

tar xzf "$tarball"
srcdir="$(basename "$tarball" .tar.gz)"

# out-of-tree build with no write permission
(
	trap 'chmod -R u=rwX "$srcdir"' EXIT
	chmod -R u=rX "$srcdir"
	cmake \
		${compiler:+  -D CMAKE_C_COMPILER="${compiler}"} \
		${generator:+ -G "${generator}"} \
		${strict:+    -D STRICT=ON} \
		${ut_san:+    -D UT_SAN=ON} \
		-S "$srcdir" -B ./build
	cmake --build ./build
	(cd ./build && ctest)
	DESTDIR=./sysroot cmake --install ./build --prefix /usr/verylocal
)

# This check might fail if the installation is different than expected,
# or if the spec is outdated.
warnings="$(set -x ; mtree -f "$srcdir/contrib/install.mtree" -p ./sysroot)"
if ! printf "%s" "$warnings" | cmp -s - /dev/null; then
	printf "%s\n" "$warnings" >&2
	exit 1
fi
