#!/usr/bin/env bash
set -eu

run_visibly () {
    set -x
    "$@"
    { set +x; } 2>&-
}

THIS_DIR=${BASH_SOURCE[0]%/*}
. "${THIS_DIR}"/lib/ensure-coreutils.sh
ROOT_DIR=$(readlink -f "${THIS_DIR}"/..)
cd "${ROOT_DIR}"

# These steps are based on observing `react-native run-android`
# with a command `strace -eexecve -f react-native run-android`.

run_visibly tools/gradle -q :app:installDebug "$@"

devices=(
    $(run_visibly adb devices | perl -0ne 'print "$_\n" for (/^(\S+) \s+ device$/gmx)')
)

if ! (( ${#devices[@]} )); then
    echo >&2 "No devices connected!"
    exit 1
fi

for device in "${devices[@]}"; do
    run_visibly adb -s "${device}" reverse tcp:8081 tcp:8081

    # This is the part that `react-native run-android` doesn't have the
    # option to do correctly: even when you pass a --main-activity flag,
    # it appends that value to the app ID.  So it's impossible to specify
    # the correct activity when its name doesn't begin with the full app ID.
    run_visibly adb -s "${device}" shell \
        am start -n com.zulipmobile.debug/com.zulipmobile.MainActivity
done
