#!/bin/sh
# script/e2e-container: run one command in a container with this repo at
# /work, and exit with that command's status. Our own extension to
# scripts-to-rule-them-all, used by script/test-e2e and
# script/test-e2e-firefox.
#
# It takes the arguments you would give `docker run`, minus the mount and
# the working directory:
#
#     script/e2e-container --ipc=host -e HOME=/tmp "$IMAGE" node foo.js
#
# It exists because `docker run -v "$ROOT:/work"` cannot work under Gitea
# Actions. The runner executes the job inside a container and hands it the
# host's docker socket, so the source side of a -v is resolved by the host
# daemon and not inside the job. The job's checkout lives on a docker
# volume mounted at /workspace, which is not a host path at all: measured
# on this repo's runner, `docker run -v "$PWD:/work" ... ls -la /work`
# listed an empty directory. A suite started that way dies with "Cannot
# find module" rather than testing anything.
#
# So the repo is copied in rather than mounted. That is one mechanism for
# CI and for a laptop instead of two, which matters more than the copy:
# the path CI takes is the path a developer exercises on every local run.
# The copy costs about two seconds for this tree, against a suite that
# takes tens of seconds.
#
# Nothing is copied back out. Neither suite writes anything under the repo
# — the browser profile and every temp file live under HOME, which both
# callers point at /tmp inside the container.
set -eu

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

CID=""

cleanup() {
    if [ -n "$CID" ]; then
        docker rm -f "$CID" >/dev/null 2>&1 || true
    fi
}

main() {
    if [ "$#" -eq 0 ]; then
        echo "e2e-container: usage: e2e-container <docker-run-arg>..." >&2
        exit 2
    fi

    cd "$ROOT"

    CID="$(docker create -w /work "$@")"
    trap cleanup EXIT
    trap 'cleanup; exit 130' INT TERM

    # `docker cp <dir> <cid>:/work` with /work absent creates it and
    # copies the contents of <dir> into it. A failure here is fatal under
    # set -e, so the command below can never run against an empty /work.
    docker cp . "$CID:/work"

    # --attach propagates the container's exit status.
    docker start --attach "$CID"
}

main "$@"
