#!/usr/bin/env bash
# Host-side wrapper for capture.py. Owner-run tooling: requires `docker run`,
# which developers on this host cannot do (only the gateway / owner can).
#
# Usage: bash run.sh sites.json output-dir
#
# Runs capture.py inside mcr.microsoft.com/playwright/python:v1.49.0-noble,
# an image already present on this host (ships Python, the playwright pip
# package, and all browsers preinstalled). Nothing is installed on the host
# and nothing is added to any app image or dependency file.

set -euo pipefail

if [ "$#" -ne 2 ]; then
    echo "usage: bash run.sh sites.json output-dir" >&2
    exit 2
fi

SITES_JSON="$1"
OUT_DIR="$2"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CAPTURE_PY="${SCRIPT_DIR}/capture.py"

if [ ! -f "$SITES_JSON" ]; then
    echo "ERROR: sites.json not found: $SITES_JSON" >&2
    exit 2
fi

SITES_JSON="$(realpath "$SITES_JSON")"

mkdir -p "$OUT_DIR"
OUT_DIR="$(realpath "$OUT_DIR")"

IMAGE="mcr.microsoft.com/playwright/python:v1.49.0-noble"

# The image ships the browsers and system deps preinstalled, but not the
# `playwright` pip package itself (its build venv is deleted after browser
# install). We install it inside this throwaway --rm container at run time,
# pinned to match the image's browser version so no browser download
# happens. This touches nothing on the host and nothing in any app image --
# the container filesystem is discarded on exit.
STATUS=0
docker run --rm \
    -v "${CAPTURE_PY}:/work/capture.py:ro" \
    -v "${SITES_JSON}:/work/sites.json:ro" \
    -v "${OUT_DIR}:/work/out" \
    "${IMAGE}" \
    bash -c "pip install --quiet --root-user-action=ignore playwright==1.49.0 && python /work/capture.py /work/sites.json /work/out" || STATUS=$?

# Best-effort: the container writes output files as root, so fix perms for
# the host user if we're allowed to.
chmod 664 "${OUT_DIR}"/*.png 2>/dev/null || true

exit "$STATUS"
