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

mkdir -p "$work/.dart_tool"
cat > "$work/.dart_tool/package_config.json" <<'JSON'
{"configVersion":2,"packages":[{"name":"clock","rootUri":"file:///usr/share/dart/packages/clock","packageUri":"lib/","languageVersion":"3.4"}]}
JSON

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

void main() {
  final fixed = DateTime.utc(2020, 1, 2, 3, 4, 5);

  // Inside the zone the clock is the one we injected, and it does not move.
  withClock(Clock.fixed(fixed), () {
    if (!clock.now().isAtSameMomentAs(fixed)) {
      throw StateError("fixed clock: ${clock.now()}");
    }
    final sw = clock.stopwatch()..start();
    if (sw.elapsed != Duration.zero) {
      throw StateError("stopwatch advanced on a fixed clock: ${sw.elapsed}");
    }
    sw.stop();
  });

  // An offset clock shifts the wall clock by the given duration.
  final shifted = DateTime.now();
  withClock(Clock(() => shifted), () {
    if (!clock.now().isAtSameMomentAs(shifted)) {
      throw StateError("injected clock: ${clock.now()}");
    }
  });

  // Outside any zone the default clock tracks the wall clock.
  final before = DateTime.now().subtract(const Duration(seconds: 1));
  final now = clock.now();
  final after = DateTime.now().add(const Duration(seconds: 1));
  if (now.isBefore(before) || now.isAfter(after)) {
    throw StateError("default clock out of range: $now");
  }

  print("clock smoke test passed");
}
DART

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