#!/usr/bin/env bash set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" ROOT="$SCRIPT_DIR" print_help() { cat <<'EOF' Usage: ./install [dev|release] [module...] ./install [module...] # defaults to release ./install [dev|release] all # installs all app modules ./install all # same, defaults to release ./install [dev|release] [8|9] # Pixel 8 or Pixel 9 (by model) ./install --device=watch # Pixel Watch (by model; merged single-APK apps install their watch experience) Description: Ergonomic wrapper around ./gradlew :module:assembleRelease + adb session install. - Variant is swappable and optional (defaults to release; dev is almost never the right install — pass dev explicitly when you need it) - Supports both slash and colon notations: games/voxels == games:voxels - Supports games shorthand: ./install voxels -> games:voxels (auto-prefixed if games/ is a game) - Supports personal shorthand: ./install dooraccess -> personal:dooraccess (auto-prefixed if personal/ is a personal app) - Supports "all" keyword: ./install all -> installs every app module - Supports multiple modules in one call (single gradlew invocation) - The device argument is REQUIRED: 8|9 selects the Pixel 8 or Pixel 9 by model, --device=watch selects the Pixel Watch by model (only merged single-APK apps and :watch:wear make sense there). Also accepts --device 8|9 / --device=8|9. There is no default device. - Installs via adb package sessions with the .idsig sidecar staged, so updates to preinstalled MAOS system apps get fs-verity (plain installDev/installRelease and `adb install` never stage it and always fail those updates). Auto-passes -PversionCodeOverride when the on-device package is at the same versionCode as the build: +1 for system apps, exactly the on-device version for user apps. - Skips the push+install for an app whose built APK is byte-identical to the one already installed (size + SHA-256 compared against the on-device base.apk, probed for every package in one device query). Identical bytes mean identical versionCode and signature, so skipping cannot bypass the versionCodeOverride or fs-verity rules; any doubt (not installed, split APKs, probe/hash failure) installs normally. Skipped apps are reported separately from installed ones. INSTALL_SKIP_UNCHANGED=0 disables this. Examples: ./install release contacts -> :contacts:assembleRelease + session install ./install release games:voxels -> :games:voxels:assembleRelease + session install ./install dev games/voxels -> :games:voxels:assembleDev (slash normalized) ./install dev :games:voxels: -> :games:voxels:assembleDev (colon trimming) ./install voxels -> :games:voxels:assembleRelease (shorthand auto games:) ./install chess -> :games:chess:assembleRelease (shorthand auto games:) ./install dooraccess -> :personal:dooraccess:assembleRelease (shorthand auto personal:) ./install all -> :contacts:assembleRelease :games:chess:assembleRelease ... (all modules) ./install release all -> same as above with release variant ./install contacts calendar -> :contacts:assembleRelease :calendar:assembleRelease ./install dev contacts -> :contacts:assembleDev + session install ./install contacts dev -> :contacts:assembleDev (variant anywhere) ./install 9 maps -> :maps:assembleRelease + session install to the Pixel 9 ./install dev 8 maps -> :maps:assembleDev + session install to the Pixel 8 ./install --help ./install --dry-run contacts # prints what would run without executing gradle ./install --dry-run all # preview all modules Variant rules: - release (default): assembleRelease + session install unless explicitly asked for dev - dev: assembleDev + session install when explicitly requested - debug: BLOCKED - never use assembleDebug Notes: - NEVER uninstalls an app (no uninstall tasks) - Validates modules against app modules (those applying common-conventions-app) - Installs to the first connected device whose serial does not start with 'emulator' (unless 8|9 selects the Pixel 8 or Pixel 9) - Set INSTALL_DRY_RUN=1 or pass --dry-run for dry-run mode - INSTALL_JOBS=N: parallel session installs (default 4). INSTALL_SKIP_UNCHANGED=0: always push+install, never skip byte-identical APKs. EOF } normalize_module() { local m="$1" m="$(echo "$m" | xargs)" m="$(echo "$m" | sed -e 's|^[/:]*||' -e 's|[/:]*$||')" m="$(echo "$m" | tr '/' ':')" while echo "$m" | grep -q "::"; do m="$(echo "$m" | sed 's/::/:/g')" done m="$(echo "$m" | tr '[:upper:]' '[:lower:]')" echo "$m" } # Filesystem dir (relative to $ROOT) for a colon Gradle module. Most modules # live at their Gradle path (games:voxels -> games/voxels), but a module may # be remapped in settings.gradle.kts, e.g. # project(":watch:wear").projectDir = file("watch-wear") # so resolve through those remappings instead of assuming path == Gradle path. module_fs_path() { local mod="$1" settings_file="$ROOT/settings.gradle.kts" remapped="" if [[ -f "$settings_file" ]]; then remapped="$(grep -F "project(\":$mod\").projectDir" "$settings_file" 2>/dev/null \ | sed -nE 's/.*file\("([^"]+)"\).*/\1/p' | head -1)" fi if [[ -n "$remapped" ]]; then echo "$remapped" else echo "$mod" | tr ':' '/' fi } # Inverse of module_fs_path: filesystem dir -> colon Gradle module. fs_path_to_module() { local fs_path="$1" settings_file="$ROOT/settings.gradle.kts" remapped="" if [[ -f "$settings_file" ]]; then remapped="$(grep -E 'project\(":[^"]+"\)\.projectDir' "$settings_file" 2>/dev/null \ | sed -nE 's/.*project\(":([^"]+)"\).*file\("([^"]+)"\).*/\2 \1/p' \ | awk -v p="$fs_path" '$1 == p { print $2; exit }')" fi if [[ -n "$remapped" ]]; then echo "$remapped" else echo "$fs_path" | tr '/' ':' fi } # True when a build file applies an installable app convention (phone app or # its Wear OS companion, e.g. :watch:wear via common-conventions-wear). is_installable_build_file() { grep -qF 'id("common-conventions-app")' "$1" 2>/dev/null \ || grep -qF 'id("common-conventions-wear")' "$1" 2>/dev/null } get_app_modules_slash() { local settings_file="$ROOT/settings.gradle.kts" if [[ ! -f "$settings_file" ]]; then return fi grep -E 'include\(":[^"]+"\)' "$settings_file" 2>/dev/null \ | sed -E 's/.*include\(":([^"]+)"\).*/\1/' \ | while IFS= read -r colon_mod; do case "$colon_mod" in "" ) continue;; esac p="$(module_fs_path "$colon_mod")" if [[ -f "$ROOT/$p/build.gradle.kts" ]] && is_installable_build_file "$ROOT/$p/build.gradle.kts"; then echo "$p" fi done | sort -u } print_valid_modules() { local slash_modules slash_modules="$(get_app_modules_slash)" if [[ -z "$slash_modules" ]]; then echo " (could not discover app modules)" return fi echo "" echo "Valid app modules (slash notation for filesystem, colon for Gradle):" echo "" printf " %-30s %s\n" "Filesystem (slash)" "Gradle (colon)" printf " %-30s %s\n" "--------------------" "-------------------" while IFS= read -r sm; do case "$sm" in "" ) continue;; esac colon_mod="$(fs_path_to_module "$sm")" printf " %-30s :%s\n" "$sm" "$colon_mod" done <<< "$slash_modules" echo "" echo "Tip: Use either notation: ./install dev games/voxels OR ./install dev games:voxels" echo "Shorthand: ./install dev voxels (auto-expands to games:voxels if games/ exists)" echo " ./install dev dooraccess (auto-expands to personal:dooraccess if personal/ exists)" echo "All: ./install all (installs every app module)" } array_contains() { local needle="$1" shift local item for item in "$@"; do if [[ "$item" == "$needle" ]]; then return 0 fi done return 1 } # --- Handle zero args early (no array expansion needed) --- if [[ $# -eq 0 ]]; then print_help echo "" echo "Error: No modules specified." print_valid_modules exit 1 fi # --- Detect --help/-h/help anywhere (direct $@ loop, no array) --- for arg in "$@"; do case "$arg" in --help|-h|help) print_help exit 0 ;; esac done # --- Early DRY_RUN detection --- DRY_RUN=0 if [[ "${INSTALL_DRY_RUN:-0}" == "1" ]]; then DRY_RUN=1 fi for arg in "$@"; do if [[ "$arg" == "--dry-run" ]]; then DRY_RUN=1 fi done # --- Build FILTERED_ARGS (exclude --dry-run) --- FILTERED_ARGS=() for arg in "$@"; do if [[ "$arg" == "--dry-run" ]]; then continue fi FILTERED_ARGS+=("$arg") done # After filtering, if empty (e.g., only --dry-run was passed) if [[ ${#FILTERED_ARGS[@]} -eq 0 ]]; then print_help echo "" echo "Error: No modules specified (dry-run mode)." print_valid_modules exit 1 fi # --- Device hint: bare 8|9 anywhere, or --device 8|9 / --device=8|9 (optional) --- DEVICE_HINT="" PRESCAN_ARGS=() idx=0 while [[ $idx -lt ${#FILTERED_ARGS[@]} ]]; do arg="${FILTERED_ARGS[$idx]}" lc="$(echo "$arg" | tr '[:upper:]' '[:lower:]')" if [[ "$lc" == "--device" ]]; then if [[ $((idx + 1)) -ge ${#FILTERED_ARGS[@]} ]]; then echo "Error: --device requires a value: 8 (Pixel 8), 9 (Pixel 9) or watch (Pixel Watch)." exit 1 fi DEVICE_HINT="$(echo "${FILTERED_ARGS[$((idx + 1))]}" | tr '[:upper:]' '[:lower:]')" idx=$((idx + 2)) continue elif [[ "$lc" == --device=* ]]; then DEVICE_HINT="${lc#--device=}" idx=$((idx + 1)) continue elif [[ "$lc" == "8" || "$lc" == "9" ]]; then DEVICE_HINT="$lc" idx=$((idx + 1)) continue elif [[ "$lc" =~ ^[0-9]+$ ]]; then echo "Error: Invalid device '$arg'. Use 8 (Pixel 8), 9 (Pixel 9) or --device=watch." exit 1 fi PRESCAN_ARGS+=("$arg") idx=$((idx + 1)) done FILTERED_ARGS=("${PRESCAN_ARGS[@]}") if [[ -n "$DEVICE_HINT" && "$DEVICE_HINT" != "8" && "$DEVICE_HINT" != "9" && "$DEVICE_HINT" != "watch" ]]; then echo "Error: Invalid device '$DEVICE_HINT'. Use 8 (Pixel 8), 9 (Pixel 9) or watch (Pixel Watch)." exit 1 fi if [[ -z "$DEVICE_HINT" ]]; then echo "Error: a target device is required: pass 8 (Pixel 8), 9 (Pixel 9) or --device=watch (Pixel Watch); there is no default device." exit 1 fi # --- Arg parsing: variant detection anywhere --- VARIANT_LC="" VARIANT_COUNT=0 MODULES_RAW=() idx=0 while [[ $idx -lt ${#FILTERED_ARGS[@]} ]]; do arg="${FILTERED_ARGS[$idx]}" lc="$(echo "$arg" | tr '[:upper:]' '[:lower:]')" if [[ "$lc" == "dev" || "$lc" == "release" || "$lc" == "debug" ]]; then if [[ -z "$VARIANT_LC" ]]; then VARIANT_LC="$lc" VARIANT_COUNT=1 else if [[ "$VARIANT_LC" != "$lc" ]]; then echo "Error: Multiple distinct variants specified: '$VARIANT_LC' and '$lc'." echo "Please specify only one variant: dev or release." echo "" print_help exit 1 fi VARIANT_COUNT=$((VARIANT_COUNT + 1)) fi else MODULES_RAW+=("$arg") fi idx=$((idx + 1)) done if [[ -z "$VARIANT_LC" ]]; then VARIANT_LC="release" fi if [[ "$VARIANT_LC" == "debug" ]]; then echo "Error: 'debug' variant is blocked." echo "" echo " - Never assemble or install a debug variant" echo " - Always install the release build, unless specifically asked for dev" echo "" echo "Use 'release' (default) or 'dev' instead:" echo " ./install " echo " ./install dev " exit 1 fi if [[ ${#MODULES_RAW[@]} -eq 0 ]]; then echo "Error: No modules specified (only variant '$VARIANT_LC' found)." echo "" print_help print_valid_modules exit 1 fi # --- Normalization + Dedup + Shorthand + "all" + auto games: prefix --- NORMALIZED_MODULES=() ALL_EXPANDED=0 idx=0 while [[ $idx -lt ${#MODULES_RAW[@]} ]]; do raw="${MODULES_RAW[$idx]}" norm="$(normalize_module "$raw")" if [[ -z "$norm" ]]; then echo "Warning: Skipping empty/invalid module token '$raw' after normalization." idx=$((idx + 1)) continue fi # Handle "all" keyword - expand to every app module if [[ "$norm" == "all" ]]; then if [[ $ALL_EXPANDED -eq 0 ]]; then echo "Info: Expanding 'all' to all app modules..." all_slash="$(get_app_modules_slash)" if [[ -z "$all_slash" ]]; then echo "Error: Could not discover app modules for 'all' expansion." print_valid_modules exit 1 fi while IFS= read -r sm; do case "$sm" in "" ) continue;; esac colon_mod="$(fs_path_to_module "$sm")" # dedup for expanded modules dup=0 j=0 while [[ $j -lt ${#NORMALIZED_MODULES[@]} ]]; do if [[ "${NORMALIZED_MODULES[$j]}" == "$colon_mod" ]]; then dup=1 break fi j=$((j + 1)) done if [[ $dup -eq 0 ]]; then NORMALIZED_MODULES+=("$colon_mod") fi done <<< "$all_slash" ALL_EXPANDED=1 fi idx=$((idx + 1)) continue fi # Auto games:/personal: prefix - if token has no colon and games/ or personal/ is a valid app module, prefix it # This allows ./install voxels -> games:voxels, ./install chess -> games:chess, ./install dooraccess -> personal:dooraccess etc. if [[ "$norm" != *":"* ]]; then for auto_prefix in games personal; do pref_path="$ROOT/$auto_prefix/$norm" if [[ -f "$pref_path/build.gradle.kts" ]] && grep -qF 'id("common-conventions-app")' "$pref_path/build.gradle.kts" 2>/dev/null; then expanded="$auto_prefix:$norm" echo "Info: Expanding shorthand '$raw' ($norm) -> $expanded (found $auto_prefix/$norm)" norm="$expanded" break elif [[ ! -e "$ROOT/$norm" && -e "$ROOT/$auto_prefix/$norm" ]]; then # Fallback: if root/ doesn't exist but / does (backward compat) expanded="$auto_prefix:$norm" echo "Info: Expanding shorthand '$raw' ($norm) -> $expanded (found $auto_prefix/$norm)" norm="$expanded" break fi done fi # Dedup via index loop (bash 3.2 safe) dup=0 j=0 while [[ $j -lt ${#NORMALIZED_MODULES[@]} ]]; do if [[ "${NORMALIZED_MODULES[$j]}" == "$norm" ]]; then dup=1 break fi j=$((j + 1)) done if [[ $dup -eq 0 ]]; then NORMALIZED_MODULES+=("$norm") fi idx=$((idx + 1)) done if [[ ${#NORMALIZED_MODULES[@]} -eq 0 ]]; then echo "Error: No valid modules after normalization." print_valid_modules exit 1 fi # --- Validation --- INVALID_MODULES=() idx=0 while [[ $idx -lt ${#NORMALIZED_MODULES[@]} ]]; do mod="${NORMALIZED_MODULES[$idx]}" fs_path="$(module_fs_path "$mod")" full_path="$ROOT/$fs_path" if [[ ! -f "$full_path/build.gradle.kts" ]]; then INVALID_MODULES+=("$mod (not found: $fs_path/build.gradle.kts)") else if ! is_installable_build_file "$full_path/build.gradle.kts"; then INVALID_MODULES+=("$mod (exists but is not an app module - missing common-conventions-app)") fi fi idx=$((idx + 1)) done if [[ ${#INVALID_MODULES[@]} -gt 0 ]]; then echo "Error: Some modules are invalid:" idx=0 while [[ $idx -lt ${#INVALID_MODULES[@]} ]]; do echo " - ${INVALID_MODULES[$idx]}" idx=$((idx + 1)) done print_valid_modules exit 1 fi # --- Build Gradle tasks (assemble only; install happens below via adb sessions) --- VARIANT_CAP="$(echo "$VARIANT_LC" | awk '{print toupper(substr($0,1,1)) substr($0,2)}')" TASKS=() idx=0 while [[ $idx -lt ${#NORMALIZED_MODULES[@]} ]]; do mod="${NORMALIZED_MODULES[$idx]}" TASKS+=(":${mod}:assemble${VARIANT_CAP}") idx=$((idx + 1)) done # Safe joining without ${ARRAY[*]} under set -u when empty (should not be empty here, but guard) modules_str="" tasks_str="" idx=0 while [[ $idx -lt ${#NORMALIZED_MODULES[@]} ]]; do if [[ $idx -gt 0 ]]; then modules_str="$modules_str ${NORMALIZED_MODULES[$idx]}" else modules_str="${NORMALIZED_MODULES[$idx]}" fi idx=$((idx + 1)) done idx=0 while [[ $idx -lt ${#TASKS[@]} ]]; do if [[ $idx -gt 0 ]]; then tasks_str="$tasks_str ${TASKS[$idx]}" else tasks_str="${TASKS[$idx]}" fi idx=$((idx + 1)) done echo "Variant: $VARIANT_LC (assemble + adb session install)" echo "Modules (${#NORMALIZED_MODULES[@]}): $modules_str" echo "Gradle tasks: $tasks_str" echo "" # --- Device selection: first connected device whose serial doesn't start with 'emulator' --- ADB_BIN="" if command -v adb >/dev/null 2>&1; then ADB_BIN="adb" else for adb_base in "${ANDROID_HOME:-}" "${ANDROID_SDK_ROOT:-}" "$HOME/Android/Sdk" "$HOME/Library/Android/sdk"; do if [[ -n "$adb_base" && -x "$adb_base/platform-tools/adb" ]]; then ADB_BIN="$adb_base/platform-tools/adb" break fi done fi TARGET_SERIAL="" if [[ -n "$ADB_BIN" ]]; then # hint '' = first non-emulator device; '8' = model Pixel_8; # '9' = model Pixel_9* (covers Pixel_9 and Pixel_9_Pro_XL). while read -r dev_line; do dev_serial="$(echo "$dev_line" | awk '{print $1}')" dev_state="$(echo "$dev_line" | awk '{print $2}')" [[ "$dev_state" == "device" ]] || continue case "$dev_serial" in emulator*) continue;; esac case "$dev_serial" in "List"*) continue;; esac if [[ -z "$DEVICE_HINT" ]]; then TARGET_SERIAL="$dev_serial" break fi dev_model="$(echo "$dev_line" | sed -nE 's/.*model:([^[:space:]]+).*/\1/p')" if [[ "$DEVICE_HINT" == "8" && "$dev_model" == "Pixel_8" ]]; then TARGET_SERIAL="$dev_serial" break fi if [[ "$DEVICE_HINT" == "9" && "$dev_model" == Pixel_9* ]]; then TARGET_SERIAL="$dev_serial" break fi if [[ "$DEVICE_HINT" == "watch" && "$dev_model" == *Watch* ]]; then TARGET_SERIAL="$dev_serial" break fi done < <("$ADB_BIN" devices -l 2>/dev/null) fi if [[ -z "$ADB_BIN" ]]; then if [[ $DRY_RUN -eq 1 ]]; then echo "[DRY-RUN] Warning: adb not found; a device could not be selected." else echo "Error: adb not found; cannot select a target device." echo "Install Android platform-tools and put adb on PATH (or set ANDROID_HOME)." exit 1 fi elif [[ -n "$TARGET_SERIAL" ]]; then export ANDROID_SERIAL="$TARGET_SERIAL" if [[ -n "$DEVICE_HINT" ]]; then echo "Target device: $ANDROID_SERIAL (Pixel $DEVICE_HINT)" else echo "Target device: $ANDROID_SERIAL (first connected device not starting with 'emulator')" fi elif [[ -n "$DEVICE_HINT" ]]; then echo "Error: No connected device matching '$DEVICE_HINT' found (check 'adb devices')." exit 1 elif [[ $DRY_RUN -eq 1 ]]; then echo "[DRY-RUN] Warning: no non-emulator device connected; ANDROID_SERIAL not set." else echo "Error: No non-emulator device connected." echo "Connect a physical device (check 'adb devices'); refusing to install to an emulator." exit 1 fi # applicationId for a module (all are string literals in build.gradle.kts). module_application_id() { sed -nE 's/^[[:space:]]*applicationId[[:space:]]*=[[:space:]]*"([^"]+)".*/\1/p' \ "$ROOT/$(module_fs_path "$1")/build.gradle.kts" | head -1 } # APK built for a module; output-metadata.json names the file authoritatively # (nested modules like cast:tv build tv-dev.apk, not cast-tv-dev.apk). built_apk() { local mod="$1" fs_path out_dir meta base_name file_name fs_path="$(module_fs_path "$mod")" out_dir="$ROOT/$fs_path/build/outputs/apk/$VARIANT_LC" meta="$out_dir/output-metadata.json" base_name="${mod##*:}" file_name="$base_name-$VARIANT_LC.apk" if [[ -f "$meta" ]]; then local found found="$(grep -oE '"outputFile"[[:space:]]*:[[:space:]]*"[^"]+"' "$meta" | head -1 | sed -E 's/.*\"([^\"]+)\"$/\1/')" [[ -n "$found" ]] && file_name="$found" fi if [[ -f "$out_dir/$file_name" ]]; then echo "$out_dir/$file_name" return 0 fi return 1 } # Run one adb command against the target device, riding out a dropped # network-adb transport: the forwarded endpoint the phone hangs off # (127.0.0.1:15556) loses the device for a few seconds at a time under # install load, and without this a single drop fails every remaining app # in the run. Combined output goes to stdout; reconnect notes and the # final error go to stderr (callers used to discard adb's stderr entirely, # which hid exactly this failure). adb_dev() { local attempt out for attempt in 1 2 3 4; do out="$("$ADB_BIN" -s "$TARGET_SERIAL" "$@" 2>&1)" && { printf '%s' "$out"; return 0; } if echo "$out" | grep -qiE "device '[^']*' not found|device offline|no devices/emulators"; then echo " adb: transport to $TARGET_SERIAL lost (attempt $attempt); reconnecting..." >&2 "$ADB_BIN" connect "$TARGET_SERIAL" >/dev/null 2>&1 # Bounded wait: a tunnel that stays down must fail this app, not # freeze the whole run on wait-for-device. local waited=0 while [[ $waited -lt 30 ]]; do [[ "$("$ADB_BIN" -s "$TARGET_SERIAL" get-state 2>/dev/null)" == "device" ]] && break sleep 2; waited=$((waited + 2)) done continue fi printf '%s\n' "$out" >&2 return 1 done printf '%s\n' "$out" >&2 return 1 } # on-device versionCode for a package, empty when not installed. device_version_code() { # No `head -1` here: with pipefail, head closing the pipe SIGPIPEs adb and # the failing assignment kills the script (set -e) after the first module. adb_dev shell pm list packages --show-versioncode "$1" \ | sed -nE "s/^package:${1//./\\.}[[:space:]]+versionCode:([0-9]+).*/\\1/p" } # exit 0 when the package is installed as a system app. is_system_app() { adb_dev shell pm list packages -s "$1" \ | tr -d '\r' | grep -qFx "package:$1" } install_apk_via_session() { local apk="$1" package_id="$2" cur="${3:-}" total="${4:-}" mod="${5:-}" local apk_name apk_size apk_mb session device_apk idsig device_idsig commit_out prefix local t_start t_pushed t_done push_secs total_secs push_rate mod_slug apk_name="$(basename "$apk")" apk_size="$(wc -c < "$apk" | tr -d ' ')" apk_mb="$(awk "BEGIN {printf \"%.1f\", $apk_size/1048576}")" # Stage under a per-module name: :watch and :watch:wear deliberately share # applicationId com.vayunmathur.watch, so a package-only staging name made # the two overwrite each other's pushed APK whenever they landed in the # same parallel wave (and the loser's cleanup rm deleted the winner's file # mid-install). The module slug keeps every staging file unique. mod_slug="$(printf '%s' "${mod:-$package_id}" | tr ':/' '__')" device_apk="/data/local/tmp/install_${package_id}_${mod_slug}.apk" device_idsig="$device_apk.idsig" t_start="$(date +%s)" if [[ -n "$cur" && -n "$total" ]]; then prefix="[$cur/$total] " else prefix="" fi echo "${prefix}Installing $package_id ($apk_name, ${apk_mb} MB)..." echo " ${prefix}[1/4] Pushing APK to device..." adb_dev push "$apk" "$device_apk" >/dev/null || { echo " ${prefix}Error: adb push failed for $apk_name."; return 1 } t_pushed="$(date +%s)" echo " ${prefix}[2/4] Creating install session..." session="$(adb_dev shell pm install-create -r \ | sed -nE 's/.*created install session \[([0-9]+)\].*/\1/p')" if [[ -z "$session" ]]; then echo " ${prefix}Error: could not create install session." adb_dev shell rm -f "$device_apk" >/dev/null return 1 fi # Stage the APK first, then its .idsig sidecar (V4 signature) under the # matching name. PackageManager enables fs-verity from a staged idsig, which # MAOS/GrapheneOS requires for updates to preinstalled system apps. Plain # `adb install` never stages the sidecar, so those updates always fail. echo " ${prefix}[3/4] Staging APK into session $session..." adb_dev shell pm install-write -S "$apk_size" "$session" base.apk "$device_apk" >/dev/null || { echo " ${prefix}Error: failed to stage $apk_name into session $session." adb_dev shell pm install-abandon "$session" >/dev/null adb_dev shell rm -f "$device_apk" >/dev/null return 1 } idsig="$apk.idsig" if [[ -f "$idsig" ]]; then echo " ${prefix}Staging .idsig sidecar..." if adb_dev push "$idsig" "$device_idsig" >/dev/null; then adb_dev shell pm install-write -S "$(wc -c < "$idsig" | tr -d ' ')" \ "$session" base.apk.idsig "$device_idsig" >/dev/null || \ echo " ${prefix}Warning: could not stage .idsig; system-app updates may fail fs-verity." else echo " ${prefix}Warning: could not push .idsig; system-app updates may fail fs-verity." fi # The staged sidecar is copied into the session by install-write, so its # tmp file only needs deleting once, together with the APK after commit # (one round trip instead of two). else echo " ${prefix}Warning: no .idsig sidecar next to the APK; system-app updates may fail fs-verity." fi echo " ${prefix}[4/4] Committing install session $session..." commit_out="$(adb_dev shell pm install-commit "$session")" adb_dev shell rm -f "$device_apk" "$device_idsig" >/dev/null t_done="$(date +%s)" push_secs=$((t_pushed - t_start)); if [[ $push_secs -lt 1 ]]; then push_secs=1; fi total_secs=$((t_done - t_start)); if [[ $total_secs -lt 1 ]]; then total_secs=1; fi push_rate="$(awk "BEGIN {printf \"%.1f\", $apk_size/1048576/$push_secs}")" # `pm install-commit` prints "Success" but exits 0 either way; fail on absence. if ! echo "$commit_out" | grep -qi "^Success"; then echo " ${prefix}Error: install failed for $package_id: $commit_out" return 1 fi if [[ -n "$cur" && -n "$total" ]]; then echo " Installed $package_id in ${total_secs}s (push ${push_secs}s @ ${push_rate} MB/s). [$cur/$total done]" else echo " Installed $package_id in ${total_secs}s (push ${push_secs}s @ ${push_rate} MB/s)." fi } # --- Extra Gradle args: --continue so one broken module doesn't block the rest --- GRADLE_ARGS=(--continue) gradle_args_str=" --continue" if [[ "$VARIANT_LC" == "release" && $ALL_EXPANDED -eq 1 ]]; then # Match the repo-wide R8 process cap in gradle.properties (48 single-thread # deterministic processes); a lower cap here only lengthens release builds. GRADLE_ARGS+=(-P"android.r8.maxWorkers=48") gradle_args_str="$gradle_args_str -Pandroid.r8.maxWorkers=48" fi # --- Big-build heap: gradle.properties defaults to a small daemon heap sized for # scoped work. A full-repo build ("all", ~100 modules, concurrent D8 dex merge) # OOMs on it, so escalate here — and only here (ALL_EXPANDED). -D spawns a # separate big daemon; the small one stays alive for normal builds. if [[ $ALL_EXPANDED -eq 1 ]]; then GRADLE_ARGS+=(-D"org.gradle.jvmargs=-Xmx46144m -Xms4512m -XX:MaxMetaspaceSize=1024m -XX:+UseG1GC -Dfile.encoding=UTF-8") GRADLE_ARGS+=(--max-workers=128) # Rust crates build in parallel too (the pinned toolchain is preinstalled # on the dev box, so no rustup install can race — see RustNative.kt). GRADLE_ARGS+=(-P"modernapps.cargoParallelism=16") gradle_args_str="$gradle_args_str -Dorg.gradle.jvmargs=<46g-big-build-heap> --max-workers=128 -Pmodernapps.cargoParallelism=16" fi # --- versionCodeOverride: MAOS refuses to update a system package to the same # versionCode, so an APK built from the same version.txt as the on-device OS image # can never be installed over it. Query the device once; for system apps bump to # one above the on-device version, for user apps just match it exactly # (version.txt itself stays untouched). REPO_VERSION="$(sed -n '1p' "$ROOT/version.txt" | tr -d '\r' | xargs)" NEED_BUMP="$REPO_VERSION" if [[ -n "$TARGET_SERIAL" ]]; then # Batch the device queries: one `pm list packages` for every package's # versionCode and one for the system-package set, instead of two adb # round trips per module (146 calls for `all`, ~0.3s each over the # forwarded transport — ~45s of pure latency before Gradle even starts). # Falls back to the per-package queries if a batch call returns nothing. ALL_PKG_VERSIONS="$(adb_dev shell pm list packages --show-versioncode 2>/dev/null || true)" SYSTEM_PKGS="$(adb_dev shell pm list packages -s 2>/dev/null || true)" batched_version_code() { printf '%s\n' "$ALL_PKG_VERSIONS" | awk -v k="package:$1" '$1 == k { sub(/^versionCode:/, "", $2); print $2; exit }' } batched_is_system_app() { printf '%s\n' "$SYSTEM_PKGS" | grep -qxF "package:$1" } idx=0 while [[ $idx -lt ${#NORMALIZED_MODULES[@]} ]]; do pkg="$(module_application_id "${NORMALIZED_MODULES[$idx]}")" if [[ -n "$pkg" ]]; then if [[ -n "$ALL_PKG_VERSIONS" ]]; then dev_v="$(batched_version_code "$pkg")" else dev_v="$(device_version_code "$pkg")" fi if [[ -n "$dev_v" && "$dev_v" -ge "$NEED_BUMP" ]]; then if { [[ -n "$SYSTEM_PKGS" ]] && batched_is_system_app "$pkg"; } || { [[ -z "$SYSTEM_PKGS" ]] && is_system_app "$pkg"; }; then target=$((dev_v + 1)) kind="system app" else target=$dev_v kind="user app" fi if [[ "$target" -gt "$NEED_BUMP" ]]; then NEED_BUMP=$target echo "Info: $pkg is a $kind at versionCode $dev_v on-device (>= repo $REPO_VERSION); will build with -PversionCodeOverride=$target." fi fi fi idx=$((idx + 1)) done fi if [[ "$NEED_BUMP" -gt "$REPO_VERSION" ]]; then GRADLE_ARGS+=(-P"versionCodeOverride=$NEED_BUMP") gradle_args_str="$gradle_args_str -PversionCodeOverride=$NEED_BUMP" fi if [[ $DRY_RUN -eq 1 ]]; then echo "[DRY-RUN] Would execute: $SCRIPT_DIR/gradlew $tasks_str$gradle_args_str" idx=0 while [[ $idx -lt ${#NORMALIZED_MODULES[@]} ]]; do mod="${NORMALIZED_MODULES[$idx]}" if apk="$(built_apk "$mod")"; then echo "[DRY-RUN] Would session-install $(module_application_id "$mod") from $apk" else echo "[DRY-RUN] Would session-install $(module_application_id "$mod") (APK expected after assemble)" fi idx=$((idx + 1)) done exit 0 fi echo "Running: $SCRIPT_DIR/gradlew $tasks_str$gradle_args_str" echo "" # Execute with all tasks expanded via index loop (preserving word splitting safety). # --continue: one failing module must not starve the rest of the build, and the # installer below already session-installs whichever APKs exist on failure. set +u "$SCRIPT_DIR/gradlew" --continue "${TASKS[@]}" "${GRADLE_ARGS[@]}" BUILD_EXIT=$? echo "" # Install whichever APKs were (re)built, even if sibling modules failed (--continue). FAILURES=0 SKIPPED=0 if [[ $BUILD_EXIT -ne 0 ]]; then echo "Warning: assemble reported failures; installing whatever APKs exist." fi TOTAL=${#NORMALIZED_MODULES[@]} echo "" # --- Skip-unchanged probe: one device query for every package ------------- # Pushing dominates install time (a dev `all` run pushes ~8.4 GB over the # forwarded adb transport; at the observed ~3.4 MB/s per stream that is most # of the run). When a rebuild reproduces the exact APK already installed -- # the common case for modules a change did not touch -- the push, the session # round trips and the on-device commit are all wasted work. Compare size + # SHA-256 of each built APK against the on-device base.apk: byte-identical # means same versionCode, same signature and same fs-verity state, so # skipping cannot bypass the versionCodeOverride or .idsig rules above. Any # doubt (package absent, split APKs, size/hash unavailable) falls through to # a normal install. The device hashes only when the size already matches, so # a fleet-wide probe is one adb call plus on-device hashing of candidates. SKIP_PROBE_FILE="" if [[ "${INSTALL_SKIP_UNCHANGED:-1}" != "0" && -n "$TARGET_SERIAL" ]]; then probe_specs=() idx=0 while [[ $idx -lt ${#NORMALIZED_MODULES[@]} ]]; do mod="${NORMALIZED_MODULES[$idx]}" if apk="$(built_apk "$mod")"; then probe_pkg="$(module_application_id "$mod")" if [[ -n "$probe_pkg" ]]; then probe_specs+=("$probe_pkg:$(wc -c < "$apk" | tr -d ' ')") fi fi idx=$((idx + 1)) done if [[ ${#probe_specs[@]} -gt 0 ]]; then echo "Probing on-device APKs for unchanged installs (one query for ${#probe_specs[@]} package(s))..." probe_t0="$(date +%s)" probe_cmd='for spec in '"${probe_specs[*]}"'; do p=${spec%:*}; want=${spec##*:}; paths=$(pm path "$p" 2>/dev/null); cnt=$(printf "%s" "$paths" | grep -c "^package:"); if [ "$cnt" = "1" ]; then f=${paths#package:}; f=$(printf "%s" "$f" | tr -d "\r"); sz=$(stat -c %s "$f" 2>/dev/null); sha=; if [ "$sz" = "$want" ]; then sha=$(sha256sum "$f" 2>/dev/null | cut -d" " -f1); fi; echo "SKIPCHK|$p|$sz|$sha"; else echo "SKIPCHK|$p||"; fi; done' SKIP_PROBE_FILE="$(mktemp)" if ! adb_dev shell "$probe_cmd" > "$SKIP_PROBE_FILE" 2>/dev/null; then echo " Probe failed; installing everything (no skips)." rm -f "$SKIP_PROBE_FILE" SKIP_PROBE_FILE="" else echo " Probe done in $(( $(date +%s) - probe_t0 ))s. Byte-identical apps will be skipped (INSTALL_SKIP_UNCHANGED=0 disables)." fi fi fi # device_apk_state -> " " (either may be empty). device_apk_state() { if [[ -z "$SKIP_PROBE_FILE" || ! -f "$SKIP_PROBE_FILE" ]]; then return 0 fi awk -F'|' -v p="$1" '$1 == "SKIPCHK" && $2 == p { gsub(/\r/, "", $4); print $3, $4; exit }' "$SKIP_PROBE_FILE" } host_sha256() { if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | awk '{print $1}' else shasum -a 256 "$1" | awk '{print $1}' fi } # --- Install order: largest APK first -------------------------------------- # Waves run INSTALL_JOBS at a time and wait for the slowest member, so # starting the biggest pushes first (longest-processing-time scheduling) # keeps the transport busy instead of stranding it behind one 195 MB APK in # the final wave. INSTALL_ORDER=() order_lines=() idx=0 while [[ $idx -lt ${#NORMALIZED_MODULES[@]} ]]; do if apk="$(built_apk "${NORMALIZED_MODULES[$idx]}")"; then order_lines+=("$(wc -c < "$apk" | tr -d ' ') $idx") else order_lines+=("0 $idx") fi idx=$((idx + 1)) done while read -r _ord_size ord_idx; do INSTALL_ORDER+=("$ord_idx") done < <(printf '%s\n' "${order_lines[@]}" | sort -rn) # Session installs run INSTALL_JOBS at a time (default 4): every install is # a push plus four `pm` round trips over the forwarded transport, so serial # installs spent minutes on latency alone for `all`. PackageManager accepts # concurrent sessions; pushes share the transport but overlap the round # trips. The default stays at 4: the forwarded endpoint already drops the # device for seconds at a time under install load at 4 (see adb_dev), and # per-app push/commit timings printed below now make the right value # measurable -- try INSTALL_JOBS=6 or 8 on an idle device and compare the # aggregate MB/s before raising the default. Set INSTALL_JOBS=1 for the old # serial behaviour. INSTALL_JOBS="${INSTALL_JOBS:-4}" case "$INSTALL_JOBS" in ""|*[!0-9]*|0) INSTALL_JOBS=4;; esac echo "Installing $TOTAL app(s) to $TARGET_SERIAL (${INSTALL_JOBS} at a time, largest first)..." INSTALL_T0="$(date +%s)" install_one() { local mod="$1" cur="$2" apk pkg local_size dev_state dev_size dev_sha local_sha if apk="$(built_apk "$mod")"; then pkg="$(module_application_id "$mod")" # Skip only on a full size + SHA-256 match against the installed base.apk. if [[ -n "$SKIP_PROBE_FILE" ]]; then local_size="$(wc -c < "$apk" | tr -d ' ')" dev_state="$(device_apk_state "$pkg")" dev_size="$(printf '%s' "$dev_state" | awk '{print $1}')" dev_sha="$(printf '%s' "$dev_state" | awk '{print $2}')" if [[ -n "$dev_size" && -n "$dev_sha" && "$dev_size" == "$local_size" ]]; then local_sha="$(host_sha256 "$apk" | tr '[:upper:]' '[:lower:]')" if [[ -n "$local_sha" && "$local_sha" == "$(printf '%s' "$dev_sha" | tr '[:upper:]' '[:lower:]')" ]]; then echo "[$cur/$TOTAL] Skipping $pkg (identical APK already installed, $(awk "BEGIN {printf \"%.1f\", $local_size/1048576}") MB)." return 2 fi fi fi install_apk_via_session "$apk" "$pkg" "$cur" "$TOTAL" "$mod" else echo "[$cur/$TOTAL] Error: no APK found for :${mod} (assemble failed?)." return 1 fi } if [[ "$INSTALL_JOBS" -gt 1 && $TOTAL -gt 1 ]]; then FAIL_DIR="$(mktemp -d)" SKIP_DIR="$(mktemp -d)" pos=0 oi=0 while [[ $oi -lt ${#INSTALL_ORDER[@]} ]]; do wave_end=$((oi + INSTALL_JOBS)) if [[ $wave_end -gt $TOTAL ]]; then wave_end=$TOTAL; fi while [[ $oi -lt $wave_end ]]; do idx="${INSTALL_ORDER[$oi]}" mod="${NORMALIZED_MODULES[$idx]}" pos=$((pos + 1)) ( rc=0; install_one "$mod" "$pos" || rc=$? if [[ $rc -eq 2 ]]; then touch "$SKIP_DIR/$idx"; elif [[ $rc -ne 0 ]]; then touch "$FAIL_DIR/$idx"; fi ) & oi=$((oi + 1)) done wait done FAILURES=$(find "$FAIL_DIR" -type f | wc -l | tr -d ' ') SKIPPED=$(find "$SKIP_DIR" -type f | wc -l | tr -d ' ') rm -rf "$FAIL_DIR" "$SKIP_DIR" else pos=0 oi=0 while [[ $oi -lt ${#INSTALL_ORDER[@]} ]]; do idx="${INSTALL_ORDER[$oi]}" pos=$((pos + 1)) rc=0 install_one "${NORMALIZED_MODULES[$idx]}" "$pos" || rc=$? if [[ $rc -eq 2 ]]; then SKIPPED=$((SKIPPED + 1)) elif [[ $rc -ne 0 ]]; then FAILURES=$((FAILURES + 1)) fi oi=$((oi + 1)) done fi if [[ -n "$SKIP_PROBE_FILE" ]]; then rm -f "$SKIP_PROBE_FILE" fi INSTALLED_COUNT=$((TOTAL - FAILURES - SKIPPED)) INSTALL_SECS=$(( $(date +%s) - INSTALL_T0 )) echo "" echo "Install phase: ${INSTALL_SECS}s for $TOTAL app(s): $INSTALLED_COUNT installed, $SKIPPED skipped (unchanged), $FAILURES failed." if [[ $FAILURES -gt 0 ]]; then exit 1 fi if [[ $SKIPPED -gt 0 ]]; then echo "Install complete: $INSTALLED_COUNT installed, $SKIPPED skipped (unchanged) of $TOTAL." else echo "Install complete: $TOTAL/$TOTAL installed successfully." fi exit $BUILD_EXIT