#!/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

[ -n "${PUBLISH_TAR:-}" ] || MOUNT_MODE=":ro"

$RUNC run --interactive ${OPTS:-} --volume `pwd`:/source${MOUNT_MODE:-} ${1:-docker.io/amd64/ubuntu:rolling} /bin/sh << EOF
set -ex

# go-faster apt
echo  'Acquire::Languages "none";' > /etc/apt/apt.conf.d/90nolanguages

# upgrade
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y eatmydata
eatmydata apt-get -y --purge dist-upgrade

# install build dependencies
eatmydata apt-get install -y --no-install-recommends meson git pkg-config valac libglib2.0-dev libudev-dev libgudev-1.0-dev python3-gi gobject-introspection libgirepository1.0-dev gir1.2-glib-2.0 gir1.2-gudev-1.0 gtk-doc-tools udev xserver-xorg-video-dummy xserver-xorg-input-evdev xserver-xorg-input-synaptics xinput usbutils gphoto2 valgrind

# run build as user
useradd build
su -s /bin/sh - build << EOG
set -ex
cd /source
meson setup /tmp/dbg --buildtype debug --prefix /usr -Dgtk_doc=true
cd /tmp/dbg
if meson dist --help | grep -q no-tests; then
    meson dist --no-test
else
    # HACK: force gtk-doc build for older meson releases
    DESTDIR=/tmp/inst meson install
fi
meson test -v --num-processes=1
meson test -v --num-processes=1 --setup valgrind --no-suite fails-valgrind
EOG

# install and run check-installed; make sure there is nothing on stderr (for Debian/Ubuntu autopkgtests)
meson install -C /tmp/dbg
ldconfig
su -c 'meson test -C /tmp/dbg -v --num-processes=1 --setup installed 2>/tmp/installed-err' - build
if [ -s /tmp/installed-err ]; then
    echo "installed tests have output on stderr:" >&2
    cat /tmp/installed-err >&2
    exit 1
fi

# check build without assertions
su - build <<EOG
set -ex
cd /source
meson setup /tmp/rel --buildtype release -Db_ndebug=true --prefix /usr -Dgtk_doc=true
meson test -C /tmp/rel -v --num-processes=1
EOG

# copy release tarball to outside for the release that .travis.yml releases on
if [ -n "${PUBLISH_TAR:-}" ]; then
    cp /tmp/dbg/meson-dist/umockdev-*.tar.xz /source
fi
EOF
