#!/bin/bash
# xcresult-demo.sh: a macOS test run with a per-run result bundle, read back with xcresulttool and jq.
# Needs spm/ from ./spm-demo.sh. Expected: xcodebuild exits 65 (one deliberate failure); jq prints two lines.
set -u
cd "$(dirname "$0")"
command -v jq > /dev/null || { echo "jq is required" >&2; exit 2; }
[ -d spm/wt-1 ] || { echo "run ./spm-demo.sh first" >&2; exit 2; }
run="$PWD/results/xcresult/$(date +%Y%m%d-%H%M%S)-$(uuidgen)"; mkdir -p "$run"
(cd spm/wt-1 && xcodebuild test -scheme PkgDemo-Package -destination 'platform=macOS,arch=arm64' \
   -derivedDataPath "$PWD/../dd-1" -clonedSourcePackagesDirPath "$PWD/../clones-1" \
   -resultBundlePath "$run/test.xcresult" > "$run/xcodebuild.log" 2>&1)
status=$?
echo "xcodebuild exit $status; log $run/xcodebuild.log"
set -o pipefail
if [ -d "$run/test.xcresult" ]; then
  xcrun xcresulttool get test-results summary --path "$run/test.xcresult" \
    | jq -r '"\(.result): \(.passedTests) passed, \(.failedTests) failed",
             (.testFailures[] | "\(.testIdentifierString): \(.failureText)")' \
    || echo "could not read $run/test.xcresult" >&2
  du -sh "$run/test.xcresult"
else
  echo "no result bundle; read $run/xcodebuild.log" >&2
fi
