#!/bin/bash
# Build and run the iOS test app on a simulator.
# The app runs the shared suite from src/tests/ios.rs then exits; pass/fail is the
# 'Finished unit tests' marker, matching how the Android runner reports.
set -euo pipefail
SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
cd "$SCRIPTDIR/.."

BUNDLE_ID="com.keyring-manager.keyring-ios-test"
DEVICE=${DEVICE:-iPhone 15}
DERIVED_DATA=${DERIVED_DATA:-$PWD/target/ios_test_derived}

UDID=$(xcrun simctl list devices available | sed -n "s/^ *${DEVICE} (\([-0-9A-Fa-f]*\)).*/\1/p" | head -1)
if [ -z "$UDID" ]; then
    # CI runner images ship whatever simulators their Xcode does, so don't insist on a name.
    DEVICE=$(xcrun simctl list devices available | sed -n 's/^ *\(iPhone [^(]*[^ (]\) (.*/\1/p' | head -1)
    UDID=$(xcrun simctl list devices available | sed -n "s/^ *${DEVICE} (\([-0-9A-Fa-f]*\)).*/\1/p" | head -1)
fi
if [ -z "$UDID" ]; then
    echo "no available iphone simulator; set DEVICE= to one of:" >&2
    xcrun simctl list devices available >&2
    exit 1
fi
echo "=== simulator: ${DEVICE} (${UDID}) ==="

# 'boot' fails if it is already booted, which is fine.
xcrun simctl boot "$UDID" 2>/dev/null || true
xcrun simctl bootstatus "$UDID" -b

# The 'Cargo Build' phase runs ios_build.sh with the ios test feature and lipos the
# staticlib into target/lipo-ios-sim/<mode>, which OTHER_LDFLAGS points at.
echo "=== building ==="
# Leave signing alone: the simulator's adhoc signature carries the entitlements the
# keychain needs, and without them every SecItem call fails with errSecMissingEntitlement.
xcodebuild build \
    -project ios_test/keyring_ios_test.xcodeproj \
    -scheme keyring_ios_test \
    -configuration Debug \
    -sdk iphonesimulator \
    -destination "id=$UDID" \
    -derivedDataPath "$DERIVED_DATA" \
    -quiet

APP="$DERIVED_DATA/Build/Products/Debug-iphonesimulator/keyring_ios_test.app"
[ -d "$APP" ] || { echo "built app not found at $APP" >&2; exit 1; }

echo "=== running ==="
xcrun simctl uninstall "$UDID" "$BUNDLE_ID" 2>/dev/null || true
xcrun simctl install "$UDID" "$APP"

# Blocks until the app calls exit(0); a panic aborts before the marker is logged.
OUTPUT=$(xcrun simctl launch --console-pty "$UDID" "$BUNDLE_ID" 2>&1 || true)
echo "$OUTPUT" | grep -E "TEST:|Starting unit tests|Finished unit tests|panic|Backtrace" || true

if echo "$OUTPUT" | grep -q "Finished unit tests"; then
    echo "iOS unit tests PASSED"
else
    echo "iOS unit tests FAILED or did not complete (no 'Finished unit tests' marker)" >&2
    echo "$OUTPUT" >&2
    exit 1
fi
