#!/usr/bin/env bash
PATH=$PATH:node_modules/.bin
SCRIPT_DIR=$(cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd)

_playwright_version() {
  jq -r '.devDependencies["@playwright/test"]' "$SCRIPT_DIR/package.json" | sed -e 's/\=/v/'
}

playwright:local() {
  exec docker run \
    --interactive --tty --rm --ipc=host --net=host \
    --volume "$SCRIPT_DIR":/e2e:rw --env BASE_URL="$BASE_URL" \
    "mcr.microsoft.com/playwright:$(_playwright_version)" \
    bash -c "cd /e2e && env PROJECT_FILTER=firefox ./Taskfile _test $*"
}

playwright:ui() {
  playwright:local --ui-host=0.0.0.0
}

playwright:ci() {
  exec docker run \
    --interactive --tty --rm --ipc=host --net=host \
    --volume "$SCRIPT_DIR":/e2e:rw --env BASE_URL="$BASE_URL" \
    "mcr.microsoft.com/playwright:$(_playwright_version)" \
    bash -c "cd /e2e && ./Taskfile _test $*"
}

_test:full() {
  if ! test -f /.dockerenv; then
    echo "Don't run _test directly; use playwright:local."
  fi

  # run only in firefox first to see if there's errors and,
  # only if not, run in everything else
  env PROJECT_FILTER=firefox playwright test "$@" && \
  env PROJECT_FILTER=!firefox playwright test "$@"
}
_test() {
  if ! test -f /.dockerenv; then
    echo "Don't run _test directly; use playwright:local."
  fi

  playwright test "$@"
}

"$@"
