#!/usr/bin/env bash

set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
NORMALIZE="${ROOT}/bin/normalize-phpunit-output.sh"
TEMPORARY="$(mktemp -d)"
readonly ROOT NORMALIZE TEMPORARY

cleanup() {
  rm -rf "${TEMPORARY}"
}
trap cleanup EXIT

cat >"${TEMPORARY}/fast.txt" <<'EOF'
PHPUnit 12.5.31 by Sebastian Bergmann and contributors.

Time: 00:00.001, Memory: 18.00 MB

OK (15 tests, 42 assertions)
EOF

cat >"${TEMPORARY}/slow.txt" <<'EOF'
PHPUnit 12.5.31 by Sebastian Bergmann and contributors.

Time: 00:00.021, Memory: 18.00 MB

OK (15 tests, 42 assertions)
EOF

cat >"${TEMPORARY}/different-memory.txt" <<'EOF'
PHPUnit 12.5.31 by Sebastian Bergmann and contributors.

Time: 00:00.021, Memory: 20.00 MB

OK (15 tests, 42 assertions)
EOF

"${NORMALIZE}" "${TEMPORARY}/fast.txt" >"${TEMPORARY}/fast.normalized"
"${NORMALIZE}" "${TEMPORARY}/slow.txt" >"${TEMPORARY}/slow.normalized"
"${NORMALIZE}" "${TEMPORARY}/different-memory.txt" \
  >"${TEMPORARY}/different-memory.normalized"

cmp "${TEMPORARY}/fast.normalized" "${TEMPORARY}/slow.normalized"

if cmp -s \
  "${TEMPORARY}/fast.normalized" \
  "${TEMPORARY}/different-memory.normalized"
then
  echo "normalizer hid a non-timing difference" >&2
  exit 1
fi

grep -Fx 'Time: <elapsed>, Memory: 18.00 MB' \
  "${TEMPORARY}/fast.normalized" >/dev/null

echo "PHPUnit output normalization passed"
