#!/usr/bin/env bash
# initializes a device for testing and returns when ready. all arguments are
# passed to adb
case $- in *i*) :;; *) set -euo pipefail;; esac

# ------------------------------------------------------------------------------
declare ADB_ARGS=()

# ------------------------------------------------------------------------------
# adb with any script arguments
adb() {
  command adb ${ADB_ARGS:+"${ADB_ARGS[@]}"} "$@"
}

is-booted() {
  [[ "$(adb shell getprop sys.boot_completed|tr -d '\r')" == 1 ]]
}

wait-for-boot() {
  while ! is-booted && sleep 1; do :; done
}

wait-for-internet-ping() {
  # nc isn't always available
  adb shell 'ping -c1 wikipedia.org > /dev/null && echo ok'|
  grep -q ok
}

wait-for-internet-nc() {
  # ping always fails on the API 15 emulator
  adb shell "echo -e 'GET / HTTP/1.1\n'|nc wikipedia.org 80"|
  grep -q 'HTTP/[0-9].[0-9] 200 OK'
}

wait-for-internet() {
  wait-for-internet-nc || wait-for-internet-ping
}

unlock-screen() {
  # http://developer.android.com/reference/android/view/KeyEvent.html#KEYCODE_MENU
  declare -i KEYCODE_MENU=82
  adb shell input keyevent $KEYCODE_MENU
}

# ------------------------------------------------------------------------------
main() {
  ADB_ARGS=("$@")
  adb wait-for-device
  wait-for-boot
  wait-for-internet
  unlock-screen
}

# ------------------------------------------------------------------------------
case $- in *i*) :;; *) main "$@";; esac
Add CI script for testing emulator readiness
Add CI script for testing emulator readiness

The Android instrumentation tests are failing in a strange way after
upgrading the Android Support libraries[0]:

com.android.builder.testing.api.TestException: com.android.builder.testing.api.DeviceException: com.android.ddmlib.ShellCommandUnresponsiveException

This script performs some device readiness checks and waits as needed
before returning which allows the tests to run successfully again. This
script will be used by CI[1] once merged.

[0] https://gerrit.wikimedia.org/r/#/c/235859/
[1] https://gerrit.wikimedia.org/r/#/c/239902/

Change-Id: Ib8a04d12ec48fe03c508fcacd355daa20a92b34d
