#!/usr/bin/env bash
# Tries the files of dist/ (made by dev/build.sh) in a clean container (podman): the Debian package installs and
# its command runs, the zip is used without composer. Exits non-zero when a check fails.
#
#   tests/Packaging/check [base image]       default: Debian 12; docker.io/library/ubuntu:24.04 for another
#   CONTAINER_CONNECTION=name                run it on the podman of another machine
#   MEMORY=400m                              memory of the container
#   Both can be set in tests/.env (see tests/.env.example), after the .env of the project.

set -eo pipefail
BASE=${1:-docker.io/library/debian:bookworm}
cd "$(dirname "$0")/../.."
BASE_DIR=$PWD
[[ -f vendor/bin/bash-helpers ]] || { echo "bash-tools is not installed: composer install" >&2; exit 1; }
source vendor/bin/bash-helpers

# The environment of the project (.env) and the one of the tests (tests/.env): CONTAINER_CONNECTION, MEMORY...
ENV_SLUG=tests read_env || true
[[ -z "${CONTAINER_CONNECTION:-}" ]] || log "Podman connection: $CONTAINER_CONNECTION"

# What the container needs is sent to it as a tar stream, so it can run on any machine:
# CONTAINER_CONNECTION=name (see podman system connection) uses the podman of another one
stage=$(mktemp -d)
trap 'rm -rf "$stage"' EXIT
ln -s "$PWD/dist" "$stage/dist"
COPYFILE_DISABLE=1 tar -chf - -C "$stage" dist | podman run --rm -i --memory="${MEMORY:-400m}" "$BASE" bash -c '
tar -xf - --no-same-owner --warning=no-unknown-keyword -C /
status=0
check() { if eval "$2"; then echo "   ok: $1"; else echo "   FAILED: $1"; status=1; fi; }
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq >/dev/null
apt-get install -y -qq unzip /dist/*.deb >/dev/null 2>&1

check "the package is installed, it depends on PHP" "dpkg -s opensim-rest-php | grep -q \"^Depends: php-cli\""
check "its files are in /usr/share/opensim-rest-php" "[ -f /usr/share/opensim-rest-php/class-rest.php ] && [ -f /usr/share/opensim-rest-php/opensim-rest-cli.php ]"
check "the command runs" "opensim-rest-cli --help | grep -q Usage"
check "the library loads" "php -r \"require \\\"/usr/share/opensim-rest-php/class-rest.php\\\"; exit(class_exists(\\\"OpenSim_Rest\\\") ? 0 : 1);\""

mkdir /tmp/zip && cd /tmp/zip && unzip -q /dist/*.zip
check "the zip has the library and its vendor folder" "[ -f opensim-rest-php/class-rest.php ] && [ -f opensim-rest-php/vendor/autoload.php ]"
check "the zip has no composer.lock, no tests" "[ ! -e opensim-rest-php/composer.lock ] && [ ! -e opensim-rest-php/tests ]"
check "the client runs from the zip" "php opensim-rest-php/opensim-rest-cli.php --help | grep -q Usage"
check "the library loads through the autoloader of the zip" "php -r \"require \\\"/tmp/zip/opensim-rest-php/vendor/autoload.php\\\"; exit(class_exists(\\\"OpenSim_Rest\\\") ? 0 : 1);\""
exit $status'
