#!/bin/sh
# The test suite is only executed in autopkgtest, so we can just `npm install`
# the world, as there are too many missing dependencies.
set -e

# Ensure we have a writable home.
export HOME=/tmp/home
mkdir -p $HOME

# I really have no idea what I am doing here, but without this, imports fail.
export NODE_PRESERVE_SYMLINKS=1

if [ ! -e node_modules/.package-lock.json ]; then
    # This can be SUCH a source of headches, and I have not found a way to make
    # it work reusing the system installed modules.
    rm -rf package-lock.json node_modules
    mkdir node_modules
    ln -s /usr/share/nodejs/puppeteer/node_modules/devtools-protocol \
        node_modules/
fi

PUPPETEER_SKIP_DOWNLOAD=1 NPM_CONFIG_CACHE=/tmp/npm_cache \
    npm install

ts-node-script scripts/ensure-correct-devtools-protocol-package

# Binary to use for tests.
export BINARY=/usr/bin/chromium
# Flag tests that we are not using the embedded chromium.
export PUPPETEER_ALT_INSTALL=1
# Save browser logs.
export CHROME_LOG_FILE="$AUTOPKGTEST_ARTIFACTS/chromium.log"
export EXTRA_LAUNCH_OPTIONS='{"args": ["--enable-logging", "--v=1"]}'
# Some tests hang trying to talk to DBus, no idea why.
export DBUS_SESSION_BUS_ADDRESS=/dev/null

TEST_ARGS="--config mocha-config/puppeteer-unit-tests.js"
# Even in headless mode, some tests fail unless run with an X server.
TEST_RUNNER="xvfb-run mocha"

if [ "$DEBUG" != 1 ]; then
    $TEST_RUNNER $TEST_ARGS "$@" && exit 0
    echo
    echo "** TEST FAILURE **"
    echo "Re-running tests with full debugging"
    echo
fi

export EXTRA_LAUNCH_OPTIONS='{"args": ["--enable-logging=stderr", "--v=1"]}'
export DUMPIO=1
export DEBUG='puppeteer:*'
TEST_ARGS="$TEST_ARGS --reporter tap"

$TEST_RUNNER $TEST_ARGS "$@"
