#!/bin/sh
# Smoke test for the installed leak_tracker_flutter_testing library; runs offline.
set -eu

work=$(mktemp -d)
export HOME="$work"
trap 'rm -rf "$work"' EXIT INT TERM

DART=$(command -v dart 2>/dev/null || true)
[ -n "$DART" ] || DART=/usr/lib/dart/bin/dart
DART_AOT=${DART%/*}/dartaotruntime
[ -x "$DART_AOT" ] || DART_AOT=/usr/lib/dart/bin/dartaotruntime

# Each package gets the language version its own pubspec asks for.
json=""
add_pkg() {
	dir="/usr/share/dart/packages/$1"
	lv=$(LC_ALL=C grep -E "^  sdk:" "$dir/pubspec.yaml" 2>/dev/null | LC_ALL=C grep -oE "[0-9]+\.[0-9]+" | head -1)
	[ -n "$lv" ] || lv=3.0
	[ -z "$json" ] || json="$json,"
	json="$json{\"name\":\"$1\",\"rootUri\":\"file://$dir\",\"packageUri\":\"lib/\",\"languageVersion\":\"$lv\"}"
}


# Reference every installed Dart package so transitive imports resolve.
for dir in /usr/share/dart/packages/*/; do
	[ -d "$dir" ] || continue
	add_pkg "$(basename "$dir")"
done

mkdir -p "$work/.dart_tool"
cat > "$work/.dart_tool/package_config.json" <<JSON
{"configVersion":2,"packages":[$json]}
JSON

cat > "$work/main.dart" <<'DART'
import 'package:flutter/widgets.dart';
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';

void main() {
  final defaults = LeakTesting.settings;
  if (defaults.ignore) {
    throw StateError('default LeakTesting.settings must not ignore leaks');
  }
  if (!defaults.withIgnoredAll().ignore) {
    throw StateError('withIgnoredAll() did not set ignore');
  }

  final traced = defaults.withDisposalStackTrace();
  if (!traced.leakDiagnosticConfig.collectStackTraceOnDisposal) {
    throw StateError('withDisposalStackTrace() did not apply');
  }

  final ignored = defaults.withIgnored(allNotDisposed: true);
  if (!ignored.ignoredLeaks.isIgnored('Probe', leakType: LeakType.notDisposed)) {
    throw StateError('withIgnored(allNotDisposed: true) did not apply');
  }

  const probe = ValueKey<String>('leak-probe');
  if (probe.value != 'leak-probe') {
    throw StateError('Flutter widgets are not usable');
  }

  print('leak_tracker_flutter_testing smoke test passed');
}

DART

# dart:ui only exists inside the Flutter engine: compile for it, then run
# under flutter_tester instead of the plain Dart VM.
ENGINE=/usr/lib/flutter-engine/linux-x64
"$DART_AOT" /usr/lib/dart/bin/snapshots/frontend_server_aot.dart.snapshot \
	--sdk-root "$ENGINE/flutter_patched_sdk/" \
	--target=flutter \
	--output-dill "$work/app.dill" \
	--packages "$work/.dart_tool/package_config.json" \
	"$work/main.dart"
"$ENGINE/flutter_tester" "$work/app.dill"
