#!/bin/sh
# script/test-e2e-firefox: build the extension and drive the real popup in
# a real Firefox inside a pinned container. The Firefox counterpart to
# script/test-e2e. Our own extension to scripts-to-rule-them-all.
#
# Deliberately NOT called by script/check or script/test, for the same
# reason as the Chrome suite: REPO_POLICIES.md caps make test at 20 seconds
# and a browser suite does not fit. The e2e workflow in
# .gitea/workflows/e2e.yml runs it on every push, as a job separate from
# check so the 20-second cap stays intact.
#
# Unlike script/test-e2e this builds its image locally, because no
# published image carries both a pinned Firefox and a matching geckodriver.
# All three external artifacts are pinned by digest inside the Dockerfile;
# see tests/e2e/firefox/Dockerfile.
set -eu

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)"

IMAGE="$("$SCRIPT_DIR/projectname")-e2e-firefox"

main() {
    cd "$ROOT"

    if ! command -v docker >/dev/null 2>&1; then
        echo "test-e2e-firefox: docker is required to run the e2e suite" >&2
        exit 1
    fi

    echo "Building extension for e2e..."
    yarn run build 2>&1

    # The build context is tests/e2e/firefox/ and holds nothing but the
    # Dockerfile: the harness itself arrives over the bind mount below, so
    # editing it never invalidates an image layer.
    echo "Building the pinned Firefox e2e image..."
    docker build -t "$IMAGE" "$ROOT/tests/e2e/firefox"

    echo "Running the Firefox e2e suite..."
    # --shm-size=1g: Firefox needs more than the default 64MB /dev/shm.
    # --network none: the suite stubs nothing, so this is what keeps the
    #   run offline and deterministic. The extension swallows its own
    #   fetch failures, so the popup flows work unchanged; see the
    #   network note in README.md. Weaker than the Chrome suite's
    #   fixture interception, and honestly so — it proves no request
    #   escaped, but it cannot report which ones were attempted.
    # --user: keep files the suite touches owned by the caller, not root.
    # HOME=/tmp: the mapped uid has no home directory in the image.
    #
    # No --privileged. Firefox's sandbox logs
    # "CanCreateUserNamespace() clone() failure: EPERM" on startup here;
    # it is cosmetic and headless Firefox runs fine without it.
    #
    # script/e2e-container is `docker run` with the repo placed at /work;
    # it copies rather than mounts, because a bind mount does not resolve
    # under Gitea Actions. See the comment at the top of that script. The
    # copy happens before the container starts, so --network none still
    # covers everything the suite does.
    "$SCRIPT_DIR/e2e-container" \
        --shm-size=1g \
        --network none \
        --user "$(id -u):$(id -g)" \
        -e HOME=/tmp \
        "$IMAGE" \
        node tests/e2e/firefox/run.js dist/firefox
}

main "$@"
