Small fix to trim output on older api versions.

Do not merge until next week!

Proof on API 22: https://ci.chromium.org/ui/p/flutter/builders/try.shadow/Linux_android_legacy%20android_platform_tests_legacy_api_shard_5%20master/1/overview

Bug: https://github.com/flutter/flutter/issues/138267
Change-Id: I74e449357d05ed91540ca6c0a827bd7cfcae3983
Reviewed-on: https://flutter-review.googlesource.com/c/recipes/+/52462
Reviewed-by: Godofredo Contreras <godofredoc@google.com>
Commit-Queue: Ricardo Amador <ricardoamador@google.com>
diff --git a/recipe_modules/android_virtual_device/resources/avd_setup.sh b/recipe_modules/android_virtual_device/resources/avd_setup.sh
index 340e0e4..114c289 100644
--- a/recipe_modules/android_virtual_device/resources/avd_setup.sh
+++ b/recipe_modules/android_virtual_device/resources/avd_setup.sh
@@ -8,19 +8,61 @@
 #
 # Usage: ./avd_setup.sh <path-to-adb-executable>
 
-$1 kill-server
-$1 start-server
-$1 wait-for-device
-# Wait for avd to reach home screen
-$1 -s emulator-5554 shell 'while [[ -z $(getprop sys.boot_completed) ]]; do sleep 1; done;'
-$1 devices
+set -x
+
+# Monitor but it appears the device is always ready within a couple seconds.
+readonly WAIT_ITERS=60
+
+function wait_for_device_ready() {
+    local adb=${1}
+
+    local ready=1
+    # Wait for avd to reach home screen
+    for((i=0; i<${WAIT_ITERS}; i++)); do
+        out=$(${adb} -s emulator-5554 shell 'getprop sys.boot_completed' | tr -d '[:space:]')
+        if [[ "${out}" = "1" ]]; then
+            echo "Device is ready."
+            ready=0
+            break
+        else
+            echo "Device is not ready."
+            echo "output: ${out}"
+            sleep 1
+        fi
+    done
+
+    if [[ ${ready} -eq 1 ]]; then
+        echo "Device was not ready in time."
+        exit 1
+    fi
+}
+
+# path to the adb executable
+adb=${1}
+
+which ${adb}
+if [[ $? -eq 1 ]]; then
+    echo "Unable to locate adb on path."
+fi
+
+# when you run any adb command and the server is not up it will start it.
+${adb} start-server
+${adb} devices
+${adb} wait-for-device
+wait_for_device_ready ${adb}
+${adb} devices
 # Set the density DPI
-$1 shell wm density 400
+${adb} shell wm density 400
 # unlock avd
-$1 shell input keyevent 82
+${adb} shell input keyevent 82
 # Ensure developer mode is enabled
-$1 shell settings put global development_settings_enabled 1
+${adb} shell settings put global development_settings_enabled 1
 # Enable MTP file transfer
-$1 shell svc usb setFunctions mtp
+${adb} shell svc usb setFunctions mtp
 # Wait for device to boot and unlock device's screen.
-$1 wait-for-device shell 'while [[ -z $(getprop sys.boot_completed) ]]; do sleep 1; done; input keyevent 82'
+wait_for_device_ready ${adb}
+${adb} shell input keyevent 82
+
+# clear exit signal for the LUCI ci.
+echo "Emulator ready."
+exit 0
\ No newline at end of file