# Builds an Android app and runs it on an emulator or on a connected phone or tablet.
# Written by Edit's Run menu, which runs it in the Gradle project's folder:
#   sh android.sh emulator|device|test|release|studio <:module>
set -e
mode=$1 module=$2

say() { printf '\033[2m%s\033[0m\n' "$*"; }
fail() { printf '%s\n' "$*" >&2; exit 1; }

windows=
case $(uname) in
Darwin) studio_app="/Applications/Android Studio.app" cache="$HOME/Library/Caches/runnables" ;;
MINGW* | MSYS* | CYGWIN*)
	# Git for Windows' bash: Windows' own folders, in its path form.
	windows=1
	local_app=$(cygpath -u "$LOCALAPPDATA")
	programs=$(cygpath -u "$PROGRAMFILES")
	studio_app= cache="$local_app/runnables"
	;;
*) studio_app= cache="${XDG_CACHE_HOME:-$HOME/.cache}/runnables" ;;
esac

if [ "$mode" = studio ]; then
	if [ -n "$studio_app" ] && [ -d "$studio_app" ]; then
		exec open -a "$studio_app" "$PWD"
	fi
	if [ -n "$windows" ] && [ -x "$programs/Android/Android Studio/bin/studio64.exe" ]; then
		"$programs/Android/Android Studio/bin/studio64.exe" "$(cygpath -w "$PWD")" >/dev/null 2>&1 &
		exit 0
	fi
	for studio in studio studio.sh "$HOME/android-studio/bin/studio.sh" /opt/android-studio/bin/studio.sh; do
		if command -v "$studio" >/dev/null 2>&1; then
			nohup "$studio" "$PWD" >/dev/null 2>&1 &
			exit 0
		fi
	done
	fail "Android Studio isn't installed. Get it from https://developer.android.com/studio"
fi

# The SDK: ANDROID_HOME, then local.properties, then where Android Studio puts it.
sdk=${ANDROID_HOME:-${ANDROID_SDK_ROOT:-}}
if [ -z "$sdk" ] && [ -f local.properties ]; then
	sdk=$(sed -n 's/^sdk\.dir=//p' local.properties | sed 's/\\:/:/g; s/\\\\/\\/g' | tail -1)
fi
[ -z "$sdk" ] || [ -z "$windows" ] || sdk=$(cygpath -u "$sdk")
for guess in "$HOME/Library/Android/sdk" "$HOME/Android/Sdk" ${windows:+"$local_app/Android/Sdk"}; do
	[ -n "$sdk" ] || [ ! -d "$guess" ] || sdk=$guess
done
[ -n "$sdk" ] && [ -d "$sdk" ] || fail "No Android SDK found. Install Android Studio, or set ANDROID_HOME."
adb="$sdk/platform-tools/adb"
[ -x "$adb" ] || fail "The Android SDK has no platform tools. Add them in Android Studio's SDK Manager."

# Gradle runs on the JDK Android Studio ships with, unless JAVA_HOME names another.
if [ -z "${JAVA_HOME:-}" ]; then
	for jbr in "$studio_app/Contents/jbr/Contents/Home" "$HOME/android-studio/jbr" /opt/android-studio/jbr ${windows:+"$programs/Android/Android Studio/jbr"}; do
		if [ -x "$jbr/bin/java" ]; then
			export JAVA_HOME="$jbr"
			break
		fi
	done
fi
if [ -x ./gradlew ]; then
	gradle=./gradlew
elif [ -f ./gradlew ]; then
	gradle="sh ./gradlew"
elif command -v gradle >/dev/null 2>&1; then
	gradle=gradle
else
	fail "This project has no Gradle wrapper, and Gradle isn't installed."
fi

hash=$(printf '%s' "$PWD$module" | cksum | cut -d' ' -f1)
remembered="$cache/emulator-$hash"

# Serials of what adb sees, one per line: emulators or real devices, ready to use.
serials() {
	"$adb" devices | awk -v want="$1" 'NR > 1 && $2 == "device" {
		emulator = $1 ~ /^emulator-/
		if ((want == "emulator") == emulator) print $1
	}'
}
avd_of() { "$adb" -s "$1" emu avd name 2>/dev/null | head -1 | tr -d '\r'; }

# EDIT_EMULATOR (an AVD's name or a serial); else the one this project ran on last, when it's
# running; else a running emulator; else the AVD this project ran on last, or the first one, booted.
pick_emulator() {
	running=$(serials emulator)
	serial= avd=
	want=${EDIT_EMULATOR:-}
	if [ -z "$want" ] && [ -f "$remembered" ]; then
		want=$(cat "$remembered")
	fi
	if [ -n "$want" ]; then
		for candidate in $running; do
			if [ "$candidate" = "$want" ] || [ "$(avd_of "$candidate")" = "$want" ]; then
				serial=$candidate
				break
			fi
		done
	fi
	if [ -z "$serial" ] && [ -z "${EDIT_EMULATOR:-}" ] && [ -n "$running" ]; then
		serial=$(printf '%s\n' "$running" | head -1)
		count=$(printf '%s\n' "$running" | wc -l | tr -d ' ')
		if [ "$count" -gt 1 ]; then
			say "$count emulators are running; using $(avd_of "$serial"). Set EDIT_EMULATOR to pick another."
		fi
	fi
	if [ -z "$serial" ]; then
		boot_emulator "$want"
	fi
	avd=$(avd_of "$serial")
	name=${avd:-$serial}
	mkdir -p "$cache" && printf '%s\n' "${avd:-$serial}" >"$remembered"
}

boot_emulator() {
	emulator="$sdk/emulator/emulator"
	[ -x "$emulator" ] || fail "The Android SDK has no emulator. Add it in Android Studio's SDK Manager."
	avds=$("$emulator" -list-avds 2>/dev/null | grep -v '^INFO' || true)
	[ -n "$avds" ] || fail "No Android emulator found. Add one in Android Studio under Tools > Device Manager."
	avd=
	if [ -n "$1" ] && printf '%s\n' "$avds" | grep -qxF "$1"; then
		avd=$1
	elif [ -n "${EDIT_EMULATOR:-}" ]; then
		fail "No emulator called $EDIT_EMULATOR. These are set up: $(printf '%s\n' "$avds" | paste -sd, - | sed 's/,/, /g')"
	else
		avd=$(printf '%s\n' "$avds" | head -1)
	fi
	port=5554
	while "$adb" devices | grep -q "^emulator-$port"; do
		port=$((port + 2))
	done
	serial=emulator-$port
	say "Starting the $avd emulator…"
	# Its own session, so that Stop ends the app and leaves the emulator running.
	if command -v perl >/dev/null 2>&1; then
		perl -MPOSIX -e 'POSIX::setsid(); exec @ARGV' "$emulator" -avd "$avd" -port "$port" >/dev/null 2>&1 </dev/null &
	else
		nohup "$emulator" -avd "$avd" -port "$port" >/dev/null 2>&1 </dev/null &
	fi
	"$adb" -s "$serial" wait-for-device
	until [ "$("$adb" -s "$serial" shell getprop sys.boot_completed 2>/dev/null | tr -d '\r')" = 1 ]; do
		sleep 1
	done
}

# EDIT_DEVICE (a serial); else the first phone or tablet adb sees.
pick_device() {
	serial=${EDIT_DEVICE:-$(serials device | head -1)}
	if [ -z "$serial" ]; then
		if "$adb" devices | awk 'NR > 1 && $1 !~ /^emulator-/ && $2 == "unauthorized"' | grep -q .; then
			fail "The phone hasn't allowed this computer yet. Unlock it and allow USB debugging."
		fi
		fail "No Android phone or tablet found. Connect one with a cable or pair it for wireless debugging, with developer options on."
	fi
	name=$("$adb" -s "$serial" shell getprop ro.product.model 2>/dev/null | tr -d '\r')
	name=${name:-$serial}
}

run_app() {
	export ANDROID_SERIAL=$serial
	dir=$(printf '%s' "${module#:}" | tr : /)
	outputs="${dir:-.}/build/outputs/apk"
	say "Building $module for ${name}…"
	$gradle -q "$module:assembleDebug"
	metadata=$(find "$outputs" -name output-metadata.json -path '*debug*' ! -path '*/androidTest/*' 2>/dev/null | head -1)
	[ -n "$metadata" ] || fail "The build made no debug APK in $outputs."
	package=$(sed -n 's/.*"applicationId": *"\([^"]*\)".*/\1/p' "$metadata" | head -1)
	apks=$(dirname "$metadata")
	apk=$(sed -n 's/.*"outputFile": *"\([^"]*\)".*/\1/p' "$metadata" | head -1)
	apk="$apks/$apk"
	[ -n "$package" ] && [ -f "$apk" ] || fail "The build made no debug APK in $apks."
	say "Installing on ${name}…"
	"$adb" install -r -t "$apk" >/dev/null
	activity=$("$adb" shell cmd package resolve-activity --brief -a android.intent.action.MAIN \
		-c android.intent.category.LAUNCHER "$package" | tr -d '\r' | tail -1)
	case $activity in
	*/*) ;;
	*) fail "$package has no launcher activity to start." ;;
	esac
	"$adb" shell am force-stop "$package"
	"$adb" shell am start -n "$activity" >/dev/null
	pid=
	for _ in 1 2 3 4 5 6 7 8 9 10; do
		pid=$("$adb" shell pidof -s "$package" 2>/dev/null | tr -d '\r')
		[ -z "$pid" ] || break
		sleep 0.5
	done
	[ -n "$pid" ] || fail "$package didn't start. See: adb logcat"
	say "Running $package on $name. Stop ends it."
	# A command started with & ignores Ctrl+C, so Stop ends logcat here.
	"$adb" logcat -v brief -v color --pid="$pid" &
	logcat=$!
	trap 'kill "$logcat" 2>/dev/null; "$adb" shell am force-stop "$package"; exit 130' INT TERM HUP
	while "$adb" shell pidof -s "$package" 2>/dev/null | tr -d '\r' | grep -qx "$pid"; do
		sleep 1
	done
	kill "$logcat" 2>/dev/null || true
	say "$package ended."
}

case $mode in
emulator)
	pick_emulator
	run_app
	;;
device)
	pick_device
	run_app
	;;
release)
	# The bundle Google Play takes and an APK to install by hand, then the folder they are in.
	dir=$(printf '%s' "${module#:}" | tr : /)
	outputs="${dir:-.}/build/outputs"
	say "Building $module for release…"
	$gradle -q "$module:bundleRelease" "$module:assembleRelease"
	bundle=$(find "$outputs/bundle" -name '*.aab' -path '*elease*' 2>/dev/null | head -1)
	apk=$(find "$outputs/apk" -name '*.apk' -path '*elease*' 2>/dev/null | head -1)
	[ -n "$bundle" ] || [ -n "$apk" ] || fail "The build made no release bundle or APK in $outputs."
	[ -z "$bundle" ] || say "Bundle: $bundle"
	[ -z "$apk" ] || say "APK: $apk"
	case $apk in
	*unsigned*) say "Not signed: add a release signingConfig to $module's build.gradle before uploading to Google Play." ;;
	esac
	shown=${bundle:-$apk}
	if [ "$(uname)" = Darwin ]; then
		open -R "$shown"
	elif [ -n "$windows" ]; then
		explorer.exe "/select,$(cygpath -w "$shown")" || true
	elif command -v xdg-open >/dev/null 2>&1; then
		xdg-open "$(dirname "$shown")" >/dev/null 2>&1 &
	fi
	;;
test)
	pick_emulator
	export ANDROID_SERIAL=$serial
	say "Testing $module on ${name}…"
	exec $gradle "$module:connectedDebugAndroidTest"
	;;
*)
	fail "Unknown mode: $mode"
	;;
esac
