#!/bin/bash
# Run the upstream test suite (run-tests.php) from the unpacked source tree
# against the installed php8.5 packages.
set -e -o pipefail

PHP=/usr/bin/php8.5
CGI=/usr/bin/php-cgi8.5

# Extensions whose tests need an external service (database, LDAP, SNMP)
SKIP_EXTENSIONS="imap interbase ldap mssql mysql mysqli mysqlnd odbc pdo_dblib pdo_firebird pdo_mysql pdo_odbc pdo_pgsql pgsql snmp wddx"

# Some of the debian/patches fix the tests
if [ -s debian/patches/series ] && [ ! -e .pc/applied-patches ]; then
    echo "debian/patches are not applied, run the tests from the unpacked source package"
    exit 1
fi

tmp=${AUTOPKGTEST_TMP:-$(mktemp -d)}
results=${AUTOPKGTEST_ARTIFACTS:-$tmp}/test-results.txt
mkdir -p "$tmp/modules" "$tmp/sessions" "$tmp/home"

# run-tests.php collects the tests of every module in extension_dir,
# so only the tested extensions are linked there; opcache is a Zend
# extension that run-tests.php loads for the tests that need it
extension_dir=$("$PHP" -n -r 'echo ini_get("extension_dir");')
extensions=()
for f in "$extension_dir"/*.so; do
    ext=$(basename "$f" .so)
    [ -d "ext/$ext/tests" ] || continue
    case " $SKIP_EXTENSIONS " in *" $ext "*) continue ;; esac
    ln -sf "$f" "$tmp/modules/"
    [ "$ext" != "opcache" ] || continue
    extensions+=(-d "extension=$ext.so")
done
if [ ${#extensions[@]} -eq 0 ]; then
    echo "no extensions to test found in $extension_dir"
    exit 1
fi

# run-tests.php runs the tests in parallel since PHP 7.4
jobs=()
if grep -q TEST_PHP_WORKER run-tests.php; then
    jobs=("-j$(nproc)")
fi

status=0
env NO_INTERACTION=1 NO_COLOR=1 REPORT_EXIT_STATUS=1 \
    SKIP_ONLINE_TESTS=1 SKIP_IO_CAPTURE_TESTS=1 \
    HOME="$tmp/home" \
    TEST_PHP_EXECUTABLE="$PHP" \
    TEST_PHP_CGI_EXECUTABLE="$CGI" \
    "$PHP" -n run-tests.php \
        "${jobs[@]}" \
        -n \
        -d extension_dir="$tmp/modules/" \
        -d session.save_path="$tmp/sessions" \
        "${extensions[@]}" 2>&1 | tee "$results" || status=$?

# Show the output of the failed tests
find Zend ext sapi tests -name '*.log' | sort | while read -r log; do
    echo
    echo "$log:"
    cat "$log"
    echo
done | tee -a "$results"

# run-tests.php stops without a summary when it hits an internal error
if ! grep -q '^TEST RESULT SUMMARY' "$results"; then
    echo "run-tests.php did not finish"
    exit 1
fi

exit $status
