#!/bin/sh
# Smoke test for the installed process 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

# Register every installed Dart package, so transitive dependencies resolve.
mkdir -p "$work/.dart_tool"
{
  printf '{"configVersion":2,"packages":['
  first=1
  for dir in /usr/share/dart/packages/*/; do
    name=$(basename "$dir")
    [ "$first" -eq 1 ] || printf ','
    first=0
    printf '{"name":"%s","rootUri":"file:///usr/share/dart/packages/%s","packageUri":"lib/"}' "$name" "$name"
  done
  printf ']}\n'
} > "$work/.dart_tool/package_config.json"

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

void main() {
  const pm = LocalProcessManager();
  final result = pm.runSync(const <String>["true"]);
  if (result.exitCode != 0) {
    throw StateError("exitCode: ${result.exitCode}");
  }
  final failing = pm.runSync(const <String>["false"]);
  if (failing.exitCode == 0) {
    throw StateError("false should exit non-zero");
  }
  print("process smoke test passed");
}
DART

cd "$work"
"$DART" run main.dart
