File size: 25,468 Bytes
9c12830
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
#!/usr/bin/env bash
# Bash 5.3+ can deadlock writing heredoc pipes on macOS before the reader starts.
if [[ ${OSTYPE:-} == darwin* && $BASH != /bin/bash ]] && ((BASH_VERSINFO[0] > 5 || (BASH_VERSINFO[0] == 5 && BASH_VERSINFO[1] >= 3))); then
  exec /bin/bash "$0" "$@"
fi
set -euo pipefail

usage() {
  cat <<'EOF'
Usage:
  scripts/android-screenshots.sh [--form-factor all|phone|wear] [--device <adb-serial>] [--avd <name>] [--locale en-US] [--skip-build] [--skip-install] [--keep-emulator] [--dry-run]

Builds and installs the phone and Wear OS debug apps on matching emulators,
launches production screens with deterministic local fixture state, and writes
Google Play screenshots under:
  apps/android/fastlane/metadata/android/<locale>/images/phoneScreenshots/
  apps/android/fastlane/metadata/android/<locale>/images/wearScreenshots/

Capture evidence is saved under:
  .artifacts/android-screenshots/latest/

By default, the script captures both form factors using retained Pixel 2 and
Wear OS Large Round AVDs. Use --form-factor with --avd or --device to capture
one form factor on an explicitly selected emulator.
EOF
}

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ANDROID_DIR="${ROOT_DIR}/apps/android"
DEFAULT_SCREENSHOT_AVD="OpenClaw_Screenshots_API36"
DEFAULT_SCREENSHOT_DEVICE_PROFILE="pixel_2"
DEFAULT_WEAR_SCREENSHOT_AVD="OpenClaw_Wear_Screenshots_API34"
DEFAULT_WEAR_SCREENSHOT_DEVICE_PROFILE="wearos_large_round"
case "$(uname -m)" in
  arm64|aarch64) DEFAULT_SCREENSHOT_ABI="arm64-v8a" ;;
  *) DEFAULT_SCREENSHOT_ABI="x86_64" ;;
esac
DEFAULT_SCREENSHOT_SYSTEM_IMAGE="system-images;android-36;google_apis;${DEFAULT_SCREENSHOT_ABI}"
DEFAULT_WEAR_SCREENSHOT_SYSTEM_IMAGE="system-images;android-34;android-wear;${DEFAULT_SCREENSHOT_ABI}"
FORM_FACTOR="${ANDROID_SCREENSHOT_FORM_FACTOR:-all}"
LOCALE="en-US"
DEVICE="${ANDROID_SCREENSHOT_DEVICE:-}"
AVD="${ANDROID_SCREENSHOT_AVD:-$DEFAULT_SCREENSHOT_AVD}"
SCREENSHOT_DEVICE_PROFILE="${ANDROID_SCREENSHOT_DEVICE_PROFILE:-$DEFAULT_SCREENSHOT_DEVICE_PROFILE}"
SCREENSHOT_SYSTEM_IMAGE="${ANDROID_SCREENSHOT_SYSTEM_IMAGE:-$DEFAULT_SCREENSHOT_SYSTEM_IMAGE}"
KEEP_EMULATOR="${ANDROID_SCREENSHOT_KEEP_EMULATOR:-0}"
SKIP_BUILD=0
SKIP_INSTALL=0
DRY_RUN=0
SCENES=(home chat settings gateway voice-wake)
OUTPUT_TYPE="phoneScreenshots"
GRADLE_ASSEMBLE_TASK=":app:assemblePlayDebug"
APP_PACKAGE="ai.openclaw.app.debug"
ACTIVITY_COMPONENT="$APP_PACKAGE/ai.openclaw.app.MainActivity"
EMULATOR_PID=""
EMULATOR_LOG=""
STARTED_EMULATOR=0
ARTIFACT_ROOT="${ROOT_DIR}/.artifacts/android-screenshots/latest"
ARTIFACT_DIR="${ARTIFACT_ROOT}/phone"
SCREENSHOT_SIZE="${ANDROID_SCREENSHOT_SIZE:-1440x2560}"
DISPLAY_OVERRIDDEN=0
ORIGINAL_WM_SIZE=""
ORIGINAL_WM_DENSITY=""
SCREENSHOT_DENSITY=""
TIMEZONE_OVERRIDDEN=0
ORIGINAL_AUTO_TIME_ZONE=""
ORIGINAL_TIME_ZONE=""
DEVICE_EXPLICIT=0
AVD_EXPLICIT=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    --)
      shift
      ;;
    --form-factor)
      FORM_FACTOR="${2:-}"
      shift 2
      ;;
    --device)
      DEVICE="${2:-}"
      DEVICE_EXPLICIT=1
      shift 2
      ;;
    --avd)
      AVD="${2:-}"
      AVD_EXPLICIT=1
      shift 2
      ;;
    --locale)
      LOCALE="${2:-}"
      shift 2
      ;;
    --skip-build)
      SKIP_BUILD=1
      shift
      ;;
    --skip-install)
      SKIP_INSTALL=1
      shift
      ;;
    --keep-emulator)
      KEEP_EMULATOR=1
      shift
      ;;
    --dry-run)
      DRY_RUN=1
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      usage
      exit 1
      ;;
  esac
done

case "$FORM_FACTOR" in
  all)
    if [[ "$DEVICE_EXPLICIT" == "1" || "$AVD_EXPLICIT" == "1" ]]; then
      echo "--device and --avd require --form-factor phone or --form-factor wear." >&2
      exit 1
    fi
    if [[ "$KEEP_EMULATOR" == "1" ]]; then
      echo "--keep-emulator requires --form-factor phone or --form-factor wear." >&2
      exit 1
    fi
    child_args=(--locale "$LOCALE")
    [[ "$SKIP_BUILD" == "1" ]] && child_args+=(--skip-build)
    [[ "$SKIP_INSTALL" == "1" ]] && child_args+=(--skip-install)
    [[ "$DRY_RUN" == "1" ]] && child_args+=(--dry-run)
    bash "$0" --form-factor phone "${child_args[@]}"
    bash "$0" --form-factor wear "${child_args[@]}"
    exit 0
    ;;
  phone)
    ;;
  wear)
    if [[ "$DEVICE_EXPLICIT" != "1" ]]; then
      DEVICE="${ANDROID_WEAR_SCREENSHOT_DEVICE:-}"
    fi
    if [[ "$AVD_EXPLICIT" != "1" ]]; then
      AVD="${ANDROID_WEAR_SCREENSHOT_AVD:-$DEFAULT_WEAR_SCREENSHOT_AVD}"
    fi
    SCREENSHOT_DEVICE_PROFILE="${ANDROID_WEAR_SCREENSHOT_DEVICE_PROFILE:-$DEFAULT_WEAR_SCREENSHOT_DEVICE_PROFILE}"
    SCREENSHOT_SYSTEM_IMAGE="${ANDROID_WEAR_SCREENSHOT_SYSTEM_IMAGE:-$DEFAULT_WEAR_SCREENSHOT_SYSTEM_IMAGE}"
    SCREENSHOT_SIZE="${ANDROID_WEAR_SCREENSHOT_SIZE:-454x454}"
    SCENES=(chat voice controls)
    OUTPUT_TYPE="wearScreenshots"
    GRADLE_ASSEMBLE_TASK=":wear:assembleDebug"
    ACTIVITY_COMPONENT="$APP_PACKAGE/ai.openclaw.wear.MainActivity"
    ARTIFACT_DIR="${ARTIFACT_ROOT}/wear"
    ;;
  *)
    echo "Invalid Android screenshot form factor: ${FORM_FACTOR}" >&2
    echo "Use all, phone, or wear." >&2
    exit 1
    ;;
esac

validate_locale() {
  local locale="$1"
  if [[ "$locale" =~ ^[A-Za-z0-9][A-Za-z0-9_-]*$ ]]; then
    return
  fi
  echo "Invalid Android screenshot locale: ${locale}" >&2
  echo "Use a locale tag like en-US or pt-BR; path separators and dot segments are not allowed." >&2
  exit 1
}

validate_locale "$LOCALE"

if [[ ! "$SCREENSHOT_SIZE" =~ ^[0-9]+x[0-9]+$ ]]; then
  echo "Invalid Android screenshot size: ${SCREENSHOT_SIZE}" >&2
  echo "Use a pixel size like 1080x1920." >&2
  exit 1
fi
SCREENSHOT_WIDTH=$((10#${SCREENSHOT_SIZE%x*}))
SCREENSHOT_HEIGHT=$((10#${SCREENSHOT_SIZE#*x}))
SCREENSHOT_MIN_DIMENSION=$((SCREENSHOT_WIDTH < SCREENSHOT_HEIGHT ? SCREENSHOT_WIDTH : SCREENSHOT_HEIGHT))
SCREENSHOT_MAX_DIMENSION=$((SCREENSHOT_WIDTH > SCREENSHOT_HEIGHT ? SCREENSHOT_WIDTH : SCREENSHOT_HEIGHT))
if (( SCREENSHOT_MIN_DIMENSION < 320 || SCREENSHOT_MAX_DIMENSION > 3840 || SCREENSHOT_MAX_DIMENSION > SCREENSHOT_MIN_DIMENSION * 2 )); then
  echo "Android screenshot size ${SCREENSHOT_SIZE} does not meet Google Play dimension and aspect-ratio limits." >&2
  exit 1
fi

cleanup_started_emulator() {
  local stopped=0

  if [[ "$STARTED_EMULATOR" != "1" || "$KEEP_EMULATOR" == "1" ]]; then
    return
  fi
  if [[ -n "${ADB_BIN:-}" && -n "${ADB_SERIAL:-}" ]]; then
    if "$ADB_BIN" -s "$ADB_SERIAL" emu kill >/dev/null 2>&1; then
      stopped=1
      local deadline=$((SECONDS + 30))
      while (( SECONDS < deadline )); do
        if ! "$ADB_BIN" devices | awk 'NR > 1 && $2 == "device" { print $1 }' | grep -Fxq "$ADB_SERIAL"; then
          break
        fi
        sleep 1
      done
    fi
  fi
  if [[ "$stopped" != "1" && -n "$EMULATOR_PID" ]]; then
    kill "$EMULATOR_PID" >/dev/null 2>&1 || true
  fi
}

restore_device_display() {
  if [[ "$DISPLAY_OVERRIDDEN" != "1" || -z "${ADB_BIN:-}" || -z "${ADB_SERIAL:-}" ]]; then
    return
  fi
  if [[ -n "$ORIGINAL_WM_SIZE" ]]; then
    "$ADB_BIN" -s "$ADB_SERIAL" shell wm size "$ORIGINAL_WM_SIZE" >/dev/null 2>&1 || true
  else
    "$ADB_BIN" -s "$ADB_SERIAL" shell wm size reset >/dev/null 2>&1 || true
  fi
  if [[ -n "$ORIGINAL_WM_DENSITY" ]]; then
    "$ADB_BIN" -s "$ADB_SERIAL" shell wm density "$ORIGINAL_WM_DENSITY" >/dev/null 2>&1 || true
  else
    "$ADB_BIN" -s "$ADB_SERIAL" shell wm density reset >/dev/null 2>&1 || true
  fi
}

restore_device_timezone() {
  if [[ "$TIMEZONE_OVERRIDDEN" != "1" || -z "${ADB_BIN:-}" || -z "${ADB_SERIAL:-}" ]]; then
    return
  fi
  if [[ -n "$ORIGINAL_TIME_ZONE" ]]; then
    "$ADB_BIN" -s "$ADB_SERIAL" shell cmd alarm set-timezone "$ORIGINAL_TIME_ZONE" >/dev/null 2>&1 || true
  fi
  if [[ "$ORIGINAL_AUTO_TIME_ZONE" == "true" || "$ORIGINAL_AUTO_TIME_ZONE" == "false" ]]; then
    "$ADB_BIN" -s "$ADB_SERIAL" shell cmd time_zone_detector set_auto_detection_enabled "$ORIGINAL_AUTO_TIME_ZONE" >/dev/null 2>&1 || true
  fi
}

cleanup_emulator_log() {
  if [[ -n "$EMULATOR_LOG" && -f "$EMULATOR_LOG" ]]; then
    rm -f "$EMULATOR_LOG"
  fi
}

cleanup() {
  restore_device_display
  restore_device_timezone
  cleanup_started_emulator
  cleanup_emulator_log
}

trap cleanup EXIT

adb_bin() {
  if [[ -n "${ADB:-}" ]]; then
    printf '%s\n' "$ADB"
    return
  fi
  if command -v adb >/dev/null 2>&1; then
    command -v adb
    return
  fi
  for sdk_root in "${ANDROID_HOME:-}" "${ANDROID_SDK_ROOT:-}" "$HOME/Library/Android/sdk"; do
    if [[ -n "$sdk_root" && -x "$sdk_root/platform-tools/adb" ]]; then
      printf '%s\n' "$sdk_root/platform-tools/adb"
      return
    fi
  done
  echo "adb not found. Install Android platform-tools or set ADB." >&2
  return 127
}

emulator_bin() {
  if [[ -n "${ANDROID_EMULATOR:-}" ]]; then
    printf '%s\n' "$ANDROID_EMULATOR"
    return
  fi
  if command -v emulator >/dev/null 2>&1; then
    command -v emulator
    return
  fi
  for sdk_root in "${ANDROID_HOME:-}" "${ANDROID_SDK_ROOT:-}" "$HOME/Library/Android/sdk"; do
    if [[ -n "$sdk_root" && -x "$sdk_root/emulator/emulator" ]]; then
      printf '%s\n' "$sdk_root/emulator/emulator"
      return
    fi
  done
  echo "Android emulator binary not found. Install the Android emulator or set ANDROID_EMULATOR." >&2
  return 127
}

avdmanager_bin() {
  if [[ -n "${AVDMANAGER:-}" ]]; then
    printf '%s\n' "$AVDMANAGER"
    return
  fi
  for sdk_root in "${ANDROID_HOME:-}" "${ANDROID_SDK_ROOT:-}" "$HOME/Library/Android/sdk"; do
    for relative_path in cmdline-tools/latest/bin/avdmanager cmdline-tools/bin/avdmanager tools/bin/avdmanager; do
      if [[ -n "$sdk_root" && -x "$sdk_root/$relative_path" ]]; then
        printf '%s\n' "$sdk_root/$relative_path"
        return
      fi
    done
  done
  if command -v avdmanager >/dev/null 2>&1; then
    command -v avdmanager
    return
  fi
  echo "avdmanager not found. Install Android SDK command-line tools or set AVDMANAGER." >&2
  return 127
}

ensure_screenshot_avd() {
  local avd="$1"
  local emulator
  local avdmanager

  emulator="$(emulator_bin)"
  if "$emulator" -list-avds | grep -Fxq "$avd"; then
    return
  fi

  avdmanager="$(avdmanager_bin)"
  echo "Creating no-cutout screenshot AVD '${avd}' from device profile '${SCREENSHOT_DEVICE_PROFILE}'." >&2
  if ! printf 'no\n' | "$avdmanager" create avd \
    --force \
    --name "$avd" \
    --package "$SCREENSHOT_SYSTEM_IMAGE" \
    --device "$SCREENSHOT_DEVICE_PROFILE"; then
    echo "Could not create Android screenshot AVD '${avd}'." >&2
    echo "Install SDK package '${SCREENSHOT_SYSTEM_IMAGE}' or set ANDROID_SCREENSHOT_SYSTEM_IMAGE." >&2
    return 1
  fi
}

connected_devices() {
  local adb="$1"
  "$adb" devices | awk 'NR > 1 && $2 == "device" { print $1 }'
}

device_count() {
  local devices="$1"
  printf '%s\n' "$devices" | sed '/^$/d' | wc -l | tr -d ' '
}

running_avd_name() {
  local adb="$1"
  local serial="$2"
  "$adb" -s "$serial" emu avd name 2>/dev/null | tr -d '\r' | sed -n '1p'
}

wait_for_single_device() {
  local adb="$1"
  local timeout_seconds="${ANDROID_SCREENSHOT_EMULATOR_TIMEOUT_SECONDS:-180}"
  local deadline=$((SECONDS + timeout_seconds))
  local devices
  local count

  while (( SECONDS < deadline )); do
    devices="$(connected_devices "$adb")"
    count="$(device_count "$devices")"
    if [[ "$count" == "1" ]]; then
      printf '%s\n' "$devices"
      return
    fi
    sleep 2
  done

  echo "Timed out waiting for exactly one Android emulator device." >&2
  "$adb" devices -l >&2 || true
  return 1
}

wait_for_boot_completed() {
  local adb="$1"
  local serial="$2"
  local timeout_seconds="${ANDROID_SCREENSHOT_EMULATOR_TIMEOUT_SECONDS:-180}"
  local deadline=$((SECONDS + timeout_seconds))
  local boot_completed

  "$adb" -s "$serial" wait-for-device
  while (( SECONDS < deadline )); do
    boot_completed="$("$adb" -s "$serial" shell getprop sys.boot_completed 2>/dev/null | tr -d '\r' || true)"
    if [[ "$boot_completed" == "1" ]]; then
      "$adb" -s "$serial" shell input keyevent 82 >/dev/null 2>&1 || true
      return
    fi
    sleep 2
  done

  echo "Timed out waiting for Android emulator boot completion on ${serial}." >&2
  return 1
}

wait_for_explicit_device() {
  local adb="$1"
  local serial="$2"
  local timeout_seconds="${ANDROID_SCREENSHOT_DEVICE_TIMEOUT_SECONDS:-30}"
  local deadline=$((SECONDS + timeout_seconds))
  local state

  while (( SECONDS < deadline )); do
    state="$("$adb" devices | awk -v serial="$serial" '$1 == serial { print $2 }')"
    if [[ "$state" == "device" ]]; then
      return
    fi
    sleep 2
  done

  if [[ -n "$state" ]]; then
    echo "Android device '${serial}' did not become usable within ${timeout_seconds}s; current adb state is '${state}'." >&2
  else
    echo "Android device '${serial}' was not found within ${timeout_seconds}s." >&2
  fi
  "$adb" devices -l >&2 || true
  return 1
}

stabilize_device_for_screenshots() {
  local adb="$1"
  local serial="$2"
  ORIGINAL_AUTO_TIME_ZONE="$("$adb" -s "$serial" shell cmd time_zone_detector is_auto_detection_enabled 2>/dev/null | tr -d '\r')"
  ORIGINAL_TIME_ZONE="$("$adb" -s "$serial" shell getprop persist.sys.timezone 2>/dev/null | tr -d '\r')"
  if [[ "$ORIGINAL_AUTO_TIME_ZONE" != "true" && "$ORIGINAL_AUTO_TIME_ZONE" != "false" ]]; then
    echo "Could not determine emulator automatic timezone setting." >&2
    return 1
  fi
  if [[ -z "$ORIGINAL_TIME_ZONE" ]]; then
    echo "Could not determine emulator timezone." >&2
    return 1
  fi
  # Arm cleanup before the first mutation; restoring an unchanged snapshot is safe.
  TIMEZONE_OVERRIDDEN=1
  # Seeded chat timestamps use the device timezone, so disable detection before
  # pinning UTC to avoid inheriting the runner's locale.
  "$adb" -s "$serial" shell cmd time_zone_detector set_auto_detection_enabled false >/dev/null
  "$adb" -s "$serial" shell cmd alarm set-timezone UTC >/dev/null
  "$adb" -s "$serial" shell settings put global window_animation_scale 0 >/dev/null 2>&1 || true
  "$adb" -s "$serial" shell settings put global transition_animation_scale 0 >/dev/null 2>&1 || true
  "$adb" -s "$serial" shell settings put global animator_duration_scale 0 >/dev/null 2>&1 || true
  "$adb" -s "$serial" shell settings put global stay_on_while_plugged_in 3 >/dev/null 2>&1 || true
  "$adb" -s "$serial" shell svc power stayon true >/dev/null 2>&1 || true
  "$adb" -s "$serial" shell input keyevent 224 >/dev/null 2>&1 || true
  "$adb" -s "$serial" shell wm dismiss-keyguard >/dev/null 2>&1 || true
  "$adb" -s "$serial" shell settings put system font_scale 1.0 >/dev/null 2>&1 || true
}

require_emulator_device() {
  local adb="$1"
  local serial="$2"
  local qemu

  qemu="$("$adb" -s "$serial" shell getprop ro.kernel.qemu 2>/dev/null | tr -d '\r')"
  if [[ "$qemu" == "1" ]]; then
    return
  fi
  echo "Android screenshot capture requires an emulator; '${serial}' is not an emulator." >&2
  echo "Pass --avd <name> or --device <emulator-serial>." >&2
  return 1
}

configure_screenshot_display() {
  local adb="$1"
  local serial="$2"
  local current_size
  local current_density
  local effective_size
  local effective_density
  local effective_width

  current_size="$("$adb" -s "$serial" shell wm size 2>/dev/null | tr -d '\r')"
  current_density="$("$adb" -s "$serial" shell wm density 2>/dev/null | tr -d '\r')"
  ORIGINAL_WM_SIZE="$(printf '%s\n' "$current_size" | sed -n 's/^Override size: //p')"
  ORIGINAL_WM_DENSITY="$(printf '%s\n' "$current_density" | sed -n 's/^Override density: //p')"
  effective_size="${ORIGINAL_WM_SIZE:-$(printf '%s\n' "$current_size" | sed -n 's/^Physical size: //p')}"
  effective_density="${ORIGINAL_WM_DENSITY:-$(printf '%s\n' "$current_density" | sed -n 's/^Physical density: //p')}"
  if [[ ! "$effective_size" =~ ^[0-9]+x[0-9]+$ || ! "$effective_density" =~ ^[0-9]+$ ]]; then
    echo "Could not determine emulator display size and density." >&2
    return 1
  fi

  effective_width=$((10#${effective_size%x*}))
  SCREENSHOT_DENSITY=$(((10#$effective_density * SCREENSHOT_WIDTH + effective_width / 2) / effective_width))
  DISPLAY_OVERRIDDEN=1
  "$adb" -s "$serial" shell wm size "$SCREENSHOT_SIZE" >/dev/null
  "$adb" -s "$serial" shell wm density "$SCREENSHOT_DENSITY" >/dev/null
  echo "Android screenshot density: ${SCREENSHOT_DENSITY} dpi"
}

boot_emulator() {
  local adb="$1"
  local avd="$2"
  local emulator
  local emulator_args
  local extra_args
  local serial

  ensure_screenshot_avd "$avd"
  emulator="$(emulator_bin)"
  EMULATOR_LOG="$(mktemp "${TMPDIR:-/tmp}/openclaw-android-screenshot-emulator.XXXXXX.log")"
  echo "No connected Android device found. Booting AVD '${avd}'." >&2
  emulator_args=(-avd "$avd" -no-window -no-audio -no-boot-anim)
  if [[ -n "${ANDROID_SCREENSHOT_EMULATOR_ARGS:-}" ]]; then
    read -r -a extra_args <<<"$ANDROID_SCREENSHOT_EMULATOR_ARGS"
    emulator_args+=(${extra_args[@]+"${extra_args[@]}"})
  fi
  "$emulator" "${emulator_args[@]}" >"$EMULATOR_LOG" 2>&1 &
  EMULATOR_PID="$!"
  STARTED_EMULATOR=1

  serial="$(wait_for_single_device "$adb")"
  wait_for_boot_completed "$adb" "$serial"
  ADB_SERIAL="$serial"
}

resolve_device() {
  local adb="$1"
  local devices
  local count
  local connected_avd

  if [[ -n "$DEVICE" ]]; then
    wait_for_explicit_device "$adb" "$DEVICE"
    ADB_SERIAL="$DEVICE"
    return
  fi
  devices="$(connected_devices "$adb")"
  count="$(device_count "$devices")"
  if [[ "$count" == "1" ]]; then
    if connected_avd="$(running_avd_name "$adb" "$devices")"; then
      if [[ "$connected_avd" != "$AVD" ]]; then
        echo "Connected emulator '${connected_avd:-unknown}' is not the screenshot AVD '${AVD}'." >&2
        echo "Stop it so the script can boot '${AVD}', or pass --device '${devices}' to override the no-cutout profile." >&2
        return 1
      fi
    fi
    ADB_SERIAL="$devices"
    return
  fi
  if [[ "$count" == "0" ]]; then
    boot_emulator "$adb" "$AVD"
    return
  else
    echo "Multiple Android devices are connected. Pass --device <adb-serial>." >&2
  fi
  return 1
}

latest_debug_apk() {
  local output_dir
  local pattern

  if [[ "$FORM_FACTOR" == "wear" ]]; then
    output_dir="${ANDROID_DIR}/wear/build/outputs/apk/debug"
    pattern='*-debug.apk'
  else
    output_dir="${ANDROID_DIR}/app/build/outputs/apk/play/debug"
    pattern='*-play-debug.apk'
  fi
  if [[ ! -d "$output_dir" ]]; then
    return 0
  fi
  find "$output_dir" -maxdepth 1 -name "$pattern" -print 2>/dev/null | sort | tail -n 1
}

scene_ready_text() {
  if [[ "$FORM_FACTOR" == "wear" ]]; then
    case "$1" in
      chat) printf '%s\n' "Release planning" ;;
      voice) printf '%s\n' "Dictate" ;;
      controls) printf '%s\n' "Gateway connected" ;;
      *)
        echo "Unknown Wear OS screenshot scene: $1" >&2
        return 1
        ;;
    esac
    return
  fi
  case "$1" in
    home) printf '%s\n' "Overview" ;;
    # The screenshot fixture seeds chat history and restores at the live edge,
    # so wait for the latest reply instead of empty-chat copy.
    chat) printf '%s\n' "The Android release is close." ;;
    settings) printf '%s\n' "OpenClaw mobile" ;;
    voice-wake) printf '%s\n' "Wake listener" ;;
    # Connected fixtures can push Add Gateway below the composed viewport, so
    # wait for the gateway detail's always-visible subtitle instead.
    gateway) printf '%s\n' "Connection between this phone and OpenClaw." ;;
    *)
      echo "Unknown Android screenshot scene: $1" >&2
      return 1
      ;;
  esac
}

wait_for_scene_ready() {
  local adb="$1"
  local serial="$2"
  local scene="$3"
  local dump_path="$4"
  local marker
  local timeout_seconds="${ANDROID_SCREENSHOT_SCENE_TIMEOUT_SECONDS:-45}"
  local deadline=$((SECONDS + timeout_seconds))

  marker="$(scene_ready_text "$scene")"
  while (( SECONDS < deadline )); do
    if "$adb" -s "$serial" exec-out uiautomator dump /dev/tty >"$dump_path" 2>/dev/null; then
      # A newly created Wear AVD may cover the resumed app with its charging
      # overlay after stay-awake is enabled. Dismiss it or first-run capture stalls.
      if [[ "$FORM_FACTOR" == "wear" ]] && grep -Fq 'com.google.android.wearable.sysui:id/charging_container' "$dump_path"; then
        "$adb" -s "$serial" shell input keyevent 4 >/dev/null 2>&1 || true
        sleep 0.5
        continue
      fi
      if grep -Fq "$marker" "$dump_path"; then
        return
      fi
    fi
    sleep 1
  done

  echo "Timed out waiting for scene '${scene}' to expose '${marker}' in the Android UI tree." >&2
  return 1
}

sips_bin() {
  if [[ -n "${SIPS:-}" ]]; then
    printf '%s\n' "$SIPS"
    return
  fi
  if command -v sips >/dev/null 2>&1; then
    command -v sips
    return
  fi
  echo "sips not found. Android release screenshots require macOS or an explicit SIPS executable." >&2
  return 127
}

normalize_capture_for_play() {
  local input_path="$1"
  local output_path="$2"
  local sips
  local description

  sips="$(sips_bin)"
  "$sips" -s format jpeg -s formatOptions best "$input_path" --out "$output_path" >/dev/null
  rm -f "$input_path"

  description="$(file "$output_path")"
  if [[ "$description" != *"${SCREENSHOT_SIZE/x/x}"* || "$description" != *"JPEG image data"* ]]; then
    echo "Invalid Google Play screenshot output: ${description}" >&2
    return 1
  fi
}

write_artifact_manifest() {
  local serial="$1"
  local avd_name
  local git_sha
  local checksum_command

  avd_name="$(running_avd_name "$ADB_BIN" "$serial")"
  git_sha="$(git -C "$ROOT_DIR" rev-parse HEAD)"
  if command -v shasum >/dev/null 2>&1; then
    checksum_command=(shasum -a 256)
  else
    checksum_command=(sha256sum)
  fi

  {
    printf 'git_sha=%s\n' "$git_sha"
    printf 'form_factor=%s\n' "$FORM_FACTOR"
    printf 'output_type=%s\n' "$OUTPUT_TYPE"
    printf 'device=%s\n' "$serial"
    printf 'avd=%s\n' "${avd_name:-unknown}"
    printf 'locale=%s\n' "$LOCALE"
    printf 'size=%s\n' "$SCREENSHOT_SIZE"
    printf 'density=%s\n' "$SCREENSHOT_DENSITY"
    printf 'format=high-quality JPEG\n'
    printf 'scenes=%s\n' "${SCENES[*]}"
    printf 'screenshots:\n'
    "${checksum_command[@]}" "$ARTIFACT_DIR"/screenshots/*.jpg
  } >"$ARTIFACT_DIR/manifest.txt"
}

OUTPUT_DIR="${ANDROID_DIR}/fastlane/metadata/android/${LOCALE}/images/${OUTPUT_TYPE}"
ADB_SERIAL=""
ADB_DISPLAY="${DEVICE:-<auto>}"

echo "Android screenshot output: ${OUTPUT_DIR}"
echo "Android screenshot artifacts: ${ARTIFACT_DIR}"
echo "Android screenshot form factor: ${FORM_FACTOR}"
echo "Android screenshot size: ${SCREENSHOT_SIZE}"
echo "Scenes: ${SCENES[*]}"
echo "ADB device: ${ADB_DISPLAY}"
echo "Screenshot AVD: ${AVD}"
echo "Screenshot device profile: ${SCREENSHOT_DEVICE_PROFILE}"
echo "Screenshot system image: ${SCREENSHOT_SYSTEM_IMAGE}"

if [[ "$DRY_RUN" == "1" ]]; then
  echo "Dry run complete. No build, install, or capture commands were executed."
  exit 0
fi

ADB_BIN="$(adb_bin)"
resolve_device "$ADB_BIN"
require_emulator_device "$ADB_BIN" "$ADB_SERIAL"
stabilize_device_for_screenshots "$ADB_BIN" "$ADB_SERIAL"
configure_screenshot_display "$ADB_BIN" "$ADB_SERIAL"
mkdir -p "$OUTPUT_DIR"
rm -f "$OUTPUT_DIR"/*.png "$OUTPUT_DIR"/*.jpg "$OUTPUT_DIR"/*.jpeg
rm -rf "$ARTIFACT_DIR"
mkdir -p "$ARTIFACT_DIR/screenshots" "$ARTIFACT_DIR/ui-dumps" "$ARTIFACT_DIR/activity-start"

if [[ "$SKIP_INSTALL" != "1" ]]; then
  if [[ "$SKIP_BUILD" != "1" ]]; then
    (
      cd "$ANDROID_DIR"
      ./gradlew "$GRADLE_ASSEMBLE_TASK"
    )
  fi
  APK_PATH="$(latest_debug_apk)"
  if [[ -z "$APK_PATH" ]]; then
    echo "No existing ${FORM_FACTOR} debug APK found. Run without --skip-build first." >&2
    exit 1
  fi
  "$ADB_BIN" -s "$ADB_SERIAL" install -r "$APK_PATH" >/dev/null
elif [[ "$SKIP_BUILD" != "1" ]]; then
  (
    cd "$ANDROID_DIR"
    ./gradlew "$GRADLE_ASSEMBLE_TASK"
  )
fi

"$ADB_BIN" -s "$ADB_SERIAL" shell pm clear "$APP_PACKAGE" >/dev/null
"$ADB_BIN" -s "$ADB_SERIAL" shell pm grant "$APP_PACKAGE" android.permission.RECORD_AUDIO >/dev/null
"$ADB_BIN" -s "$ADB_SERIAL" logcat -c >/dev/null 2>&1 || true

for scene in "${SCENES[@]}"; do
  output_path="${OUTPUT_DIR}/openclaw-${scene}.jpg"
  raw_path="${OUTPUT_DIR}/openclaw-${scene}.raw.png"
  artifact_path="${ARTIFACT_DIR}/screenshots/openclaw-${scene}.jpg"
  ui_dump_path="${ARTIFACT_DIR}/ui-dumps/openclaw-${scene}.xml"
  activity_start_path="${ARTIFACT_DIR}/activity-start/openclaw-${scene}.txt"
  "$ADB_BIN" -s "$ADB_SERIAL" shell am force-stop "$APP_PACKAGE" >/dev/null
  "$ADB_BIN" -s "$ADB_SERIAL" shell input keyevent 224 >/dev/null 2>&1 || true
  "$ADB_BIN" -s "$ADB_SERIAL" shell wm dismiss-keyguard >/dev/null 2>&1 || true
  "$ADB_BIN" -s "$ADB_SERIAL" shell am start -W \
    -n "$ACTIVITY_COMPONENT" \
    --ez openclaw.screenshotMode true \
    --es openclaw.screenshotScene "$scene" >"$activity_start_path"
  wait_for_scene_ready "$ADB_BIN" "$ADB_SERIAL" "$scene" "$ui_dump_path"
  sleep "${ANDROID_SCREENSHOT_SETTLE_SECONDS:-0.5}"
  "$ADB_BIN" -s "$ADB_SERIAL" exec-out screencap -p >"$raw_path"
  normalize_capture_for_play "$raw_path" "$output_path"
  cp "$output_path" "$artifact_path"
  echo "Captured ${output_path}"
done

"$ADB_BIN" -s "$ADB_SERIAL" logcat -d >"$ARTIFACT_DIR/logcat.txt" 2>&1 || true
if [[ -n "$EMULATOR_LOG" && -f "$EMULATOR_LOG" ]]; then
  cp "$EMULATOR_LOG" "$ARTIFACT_DIR/emulator.log"
fi
write_artifact_manifest "$ADB_SERIAL"

echo "Android screenshots written to ${OUTPUT_DIR}"
echo "Android screenshot artifacts written to ${ARTIFACT_DIR}"