#!/bin/sh
set -eu

# keep container around if $DEBUG is set
[ -n "${DEBUG:-}" ] || OPTS="--rm"

if type podman >/dev/null 2>&1; then
    RUNC=podman
else
    RUNC="sudo docker"
fi

# prepare portage volume
$RUNC run  --rm -v gentooportage:/var/db/repos/gentoo docker.io/gentoo/portage /bin/true

$RUNC run --interactive ${OPTS:-} \
  --security-opt=seccomp=unconfined \
  --volume `pwd`:/source:ro --volume gentooportage:/var/db/repos/gentoo \
  --cap-add=CAP_SYS_ADMIN --cap-add=CAP_NET_ADMIN --cap-add=CAP_SYS_PTRACE \
  docker.io/gentoo/stage3 /bin/sh -eux <<EOF
# noman/noinfo/nodoc: skip documentation, not needed for running tests
echo 'FEATURES="\${FEATURES} binpkg-request-signature noman noinfo nodoc"' >> /etc/portage/make.conf

# only allow unstable keywords for umockdev itself, to pick up dependency changes;
# unstable keywords for the whole deptree would miss most binpkgs, which only exist for stable
echo 'dev-util/umockdev ~*' >> /etc/portage/package.accept_keywords/umockdev

# install build dependencies; umockdev itself is built from source below, but all
# dependencies are binary packages, so don't pull in their transitive build dependencies
# (--getbinpkg implies --with-bdeps=n)
emerge --getbinpkg dev-util/umockdev --with-test-deps --onlydeps
# --with-bdeps=n misses umockdev's own BDEPEND, so install those explicitly: vala and meson;
# also git, "meson dist" dependency
emerge --getbinpkg dev-lang/vala dev-build/meson dev-vcs/git

git config --global safe.directory /source

cd /source
export VALAC=\$(ls /usr/bin/valac-* |sort | tail -n1)
meson setup /tmp/dbg --buildtype debug --werror

export BRITTLE_TESTS="${BRITTLE_TESTS:-}"
meson test -C /tmp/dbg -v --num-processes=1

# and test once more in the sandbox
sandbox meson test -C /tmp/dbg -v --num-processes=1
EOF

[ -n "${DEBUG:-}" ] || $RUNC volume rm gentooportage
