Modern Apps git

MAOS.git

Public
git clone https://git.maproj.org/MAOS.git
main ▾

MAOS.git / build-maos.sh

build-maos.sh699 lines · 36.1 KiBRaw
1#!/usr/bin/env bash
2#
3# build-maos.sh — one-shot(ish) MAOS builder for Pixel 7 Pro (cheetah) on a GrapheneOS tag.
4#
5# Runs everything in docs/BUILD_RUNBOOK.md EXCEPT the Windows/WSL2 setup: install deps, sync
6# the source, extract vendor files, wire in the MAOS overlay, (generate &) use signing keys,
7# build, produce a signed release, and publish OTA + web-installer artifacts to R2.
8#
9# It is phase-based and resumable — rerun a phase or the whole thing safely.
10#
11# ./build-maos.sh all # full pipeline (cheetah)
12# ./build-maos.sh sync # just one phase
13# ./build-maos.sh -d panther -t 2026110700 all # override device/tag via flags
14# ./build-maos.sh -d all all # build EVERY supported Pixel
15# ./build-maos.sh -d cheetah,panther build # a comma-separated subset
16#
17# Usage: ./build-maos.sh [-d DEVICE] [-t TAG] [-c CHANNEL] <phase...>
18# -d DEVICE Pixel codename / build target (default: cheetah)
19# - a single codename (e.g. cheetah)
20# - "all" to build every supported Pixel (see ALL_DEVICES)
21# - a comma-separated subset (e.g. cheetah,panther)
22# -t TAG GrapheneOS base tag (default: 2026110700)
23# -c CHANNEL OTA channel to publish (default: stable; stable|beta|testing)
24# phases: deps sync vendor overlay keys build release publish all
25#
26# deps/sync/keys are device-independent and run ONCE. Then vendor/overlay (prep) and build run
27# per device SEQUENTIALLY (prep touches shared source; builds share the default out/, which
28# soong's siso/product config is anchored to). release and publish then fan out ACROSS devices
29# IN PARALLEL (up to $MAOS_RELEASE_JOBS / $MAOS_PUBLISH_JOBS at once), working from each
30# device's staged target_files/otatools zips. A device that fails a pass is logged and skipped
31# for its later phases; a pass/fail summary prints at the end.
32#
33# ── Signing keys ────────────────────────────────────────────────────────────────────────
34# Keys live in ONE scrypt-encrypted file ($MAOS_KEYS_FILE), unlocked with a passphrase you
35# pass in the environment ($MAOS_KEYS_PASSPHRASE). On first run (file absent) the `keys` phase
36# generates the full key set and encrypts it into that file. On every build/release the
37# script decrypts it into RAM (/dev/shm), uses it, and shreds the plaintext on exit — the
38# keys are never written to disk in the clear.
39#
40# The key set is DEVICE-INDEPENDENT: one shared set signs every device (the GrapheneOS
41# signing scripts read keys from keys/<device>, so the release phase decrypts the set once
42# into RAM and symlinks it in as keys/<device> for whichever device is being built).
43#
44# ── Required environment ────────────────────────────────────────────────────────────────
45# MAOS_KEYS_PASSPHRASE passphrase for the encrypted key file (required for keys/build/release)
46# For publishing:
47# R2_ACCOUNT_ID, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY Cloudflare R2 creds
48#
49# ── Optional environment ────────────────────────────────────────────────────────────────
50# MAOS_KEYS_FILE=$HOME/maos-keys/maos.keys.tar.gz.scrypt encrypted key blob (shared, outside the tree)
51# MODERN_APPS_SRC=<path> Modern-Apps checkout/dir with release APKs; if unset, the 28
52# APKs are downloaded from the Modern-Apps GitHub release
53# MAOS_BUILD_VARIANT=<variant> lunch build variant (default: user; set to userdebug
54# explicitly for debuggable builds)
55# MAOS_RELEASE_JOBS=<n> how many devices to sign/package (release) in parallel (default 4).
56# MAOS_PUBLISH_JOBS=<n> how many devices to upload (publish) in parallel (default 4).
57# MAOS_BUILD_NUMBER=<n> pin the build number (default: today's UTC date + "00").
58# MAOS_TREE=<path> AOSP checkout to use (default: $HOME/maos). Lets a rented
59# build box or the release signer point at its own tree, e.g.
60# a minimal one holding only releases/<build>/ + script/.
61#
62# ── Hardcoded ─────────────────────────────────────────────────────────────────────────────
63# R2_BUCKET=maos BUILD=<tag> (matches the GrapheneOS tag)
64#
65set -euo pipefail
66
67# ---- Parameters (flags) ----
68DEVICE="cheetah"
69TAG="2026110700"
70OTA_CHANNEL="stable"
71while getopts "d:t:c:h" _opt; do
72 case "$_opt" in
73 d) DEVICE="$OPTARG" ;;
74 t) TAG="$OPTARG" ;;
75 c) OTA_CHANNEL="$OPTARG" ;;
76 h) sed -n '2,32p' "$0"; exit 0 ;;
77 *) echo "usage: $0 [-d DEVICE] [-t TAG] [-c CHANNEL] <phase...>" >&2; exit 2 ;;
78 esac
79done
80shift $((OPTIND - 1))
81
82# Every supported Pixel (fastboot codenames), kept in sync with the web installer's DEVICES
83# map (location_share_server/os_installer/installer.js). `-d all` expands to this list.
84ALL_DEVICES=(stallion rango mustang blazer frankel tegu comet komodo caiman tokay \
85 akita husky shiba felix tangorpro lynx cheetah panther bluejay raven oriole)
86
87# Expand -d into DEVICES_LIST: "all" -> every device; "a,b,c" -> that subset; else a single device.
88if [[ "$DEVICE" == "all" ]]; then
89 DEVICES_LIST=("${ALL_DEVICES[@]}")
90elif [[ "$DEVICE" == *,* ]]; then
91 IFS=',' read -r -a DEVICES_LIST <<< "$DEVICE"
92else
93 DEVICES_LIST=("$DEVICE")
94fi
95
96# ---- Hardcoded config ----
97TREE="${MAOS_TREE:-$HOME/maos}" # AOSP checkout (ext4; never /mnt/c)
98R2_BUCKET="maos" # R2 bucket / ota.maproj.org
99# BUILD starts as the tag, but the build number for a run is pinned by pin_build_number
100# (today's UTC date + "00", or $MAOS_BUILD_NUMBER) and exported as BUILD_NUMBER so every
101# parallel build shares it; resolve_build_number recovers it for standalone release/publish.
102# That pinned number — not the tag — is what finalize.sh and the artifacts are named with.
103BUILD="$TAG"
104MANIFEST_URL="https://github.com/GrapheneOS/platform_manifest.git"
105MAOS_GH="https://github.com/vayun-mathur/" # overlay repo remote (for the local manifest)
106MODERN_APPS_GH="vayun-mathur/Modern-Apps" # source of the prebuilt APKs
107APPS=(web camera pdf contacts calculator clock files photos appstore keyboard speech calendar music communicate auto euicc backup networklocation findfamily share cast setupwizard logviewer updater parentalcontrols screentime health emergency)
108
109# ---- Derived / optional-env config ----
110# ONE shared, device-independent key set (see the "Signing keys" note above).
111MAOS_KEYS_FILE="${MAOS_KEYS_FILE:-$HOME/maos-keys/maos.keys.tar.gz.scrypt}"
112MODERN_APPS_SRC="${MODERN_APPS_SRC:-}"
113
114# Plaintext keys are only ever materialized here (RAM-backed), and shredded on exit.
115KEYS_PLAIN="/dev/shm/maos-keys"
116
117# Prefer user-writable tool installs (a writable `repo` launcher so it can self-update instead
118# of warning, plus anything else we drop in ~/.local/bin) over system copies.
119export PATH="$HOME/.local/bin:$PATH"
120
121log() { printf '\n\033[1;36m==> %s\033[0m\n' "$*"; }
122warn() { printf '\033[1;33mWARN: %s\033[0m\n' "$*" >&2; }
123die() { printf '\033[1;31mERROR: %s\033[0m\n' "$*" >&2; exit 1; }
124
125# ---- Key handling (scrypt-encrypted blob <-> RAM) ----
126
127# Plaintext tarball lives only in RAM (/dev/shm) alongside KEYS_PLAIN, and is shredded.
128KEYS_TAR="$KEYS_PLAIN.tar.gz"
129
130wipe_plain_keys() {
131 for f in "$KEYS_TAR"; do [[ -f "$f" ]] && shred -u "$f" 2>/dev/null || true; done
132 if [[ -d "$KEYS_PLAIN" ]]; then
133 find "$KEYS_PLAIN" -type f -exec shred -u {} + 2>/dev/null || true
134 rm -rf "$KEYS_PLAIN"
135 fi
136 # Drop every in-tree symlink to the RAM keys we created (one keys/<device> per built device).
137 if [[ -d "$TREE/keys" ]]; then
138 for _l in "$TREE"/keys/*; do
139 [[ -L "$_l" ]] && rm -f "$_l" || true
140 done
141 fi
142}
143trap wipe_plain_keys EXIT
144
145# Keys are encrypted with scrypt (KDF) + AES-256 via the `scrypt` utility — more
146# brute-force-resistant than PBKDF2 for an offline attacker with the blob. The passphrase is
147# read from the environment, never the command line. `--passphrase env:` requires scrypt 1.3+.
148scrypt_enc() { scrypt enc --passphrase env:MAOS_KEYS_PASSPHRASE "$1" "$2"; }
149scrypt_dec() { scrypt dec --passphrase env:MAOS_KEYS_PASSPHRASE "$1" "$2"; }
150
151require_passphrase() {
152 [[ -n "${MAOS_KEYS_PASSPHRASE:-}" ]] || die "MAOS_KEYS_PASSPHRASE must be set."
153 command -v scrypt >/dev/null || die "the 'scrypt' utility is missing — run the 'deps' phase."
154}
155
156# Decrypt the shared key blob into RAM once (idempotent). The GrapheneOS signing scripts read
157# keys from keys/<device>, so link_keys symlinks this one RAM key set in per device. Splitting
158# "unlock once" from "link per device" lets the release phase run in parallel across devices
159# without racing on decryption.
160unlock_keys_shared() {
161 require_passphrase
162 [[ -f "$MAOS_KEYS_FILE" ]] || die "Key file $MAOS_KEYS_FILE not found — run the 'keys' phase first."
163 # Already unlocked this run? (releasekey.pk8 is always in the set.)
164 [[ -s "$KEYS_PLAIN/releasekey.pk8" ]] && return 0
165 log "Unlocking signing keys into RAM (shared across devices)"
166 rm -rf "$KEYS_PLAIN"; mkdir -p "$KEYS_PLAIN"; chmod 700 "$KEYS_PLAIN"
167 rm -f "$KEYS_TAR"
168 scrypt_dec "$MAOS_KEYS_FILE" "$KEYS_TAR" || die "Failed to decrypt keys (wrong passphrase?)."
169 tar xzf "$KEYS_TAR" -C "$KEYS_PLAIN"
170 shred -u "$KEYS_TAR" 2>/dev/null || rm -f "$KEYS_TAR"
171}
172
173link_keys() { # link_keys <device> — symlink the shared RAM key set in as keys/<device>
174 mkdir -p "$TREE/keys"
175 rm -rf "$TREE/keys/$1"
176 ln -s "$KEYS_PLAIN" "$TREE/keys/$1"
177}
178
179# The build number is a single value for the whole invocation (all devices in a batch share
180# it). Parallel builds each write into their own out-<device>/ dir, so we PIN the number up
181# front (exported as BUILD_NUMBER, which soong honors) instead of reading it back per build.
182# pin_build_number: default = today's UTC date + "00" (matches how the tree generates it);
183# override with MAOS_BUILD_NUMBER (e.g. to reproduce a specific dated build).
184pin_build_number() {
185 BUILD="${MAOS_BUILD_NUMBER:-$(date -u +%Y%m%d)00}"
186 export BUILD_NUMBER="$BUILD"
187 log "Build number for this run: $BUILD (override with MAOS_BUILD_NUMBER)"
188}
189
190# For phases that DIDN'T build this run (standalone release/publish), figure out which build
191# number to use: the one pinned/exported this run, else MAOS_BUILD_NUMBER, else the newest
192# out*/soong/build_number.txt, else the newest staged releases/<n>/ dir, else the tag.
193resolve_build_number() {
194 if [[ -n "${BUILD_NUMBER:-}" ]]; then BUILD="$BUILD_NUMBER"
195 elif [[ -n "${MAOS_BUILD_NUMBER:-}" ]]; then BUILD="$MAOS_BUILD_NUMBER"
196 else
197 local f n
198 f="$(ls -1t "$TREE"/out*/soong/build_number.txt 2>/dev/null | head -1 || true)"
199 if [[ -n "$f" && -f "$f" ]]; then
200 BUILD="$(cat "$f")"
201 else
202 n="$(ls -1 "$TREE/releases" 2>/dev/null | grep -E '^[0-9]+$' | sort -rn | head -1 || true)"
203 [[ -n "$n" ]] && BUILD="$n" || warn "no build number found; using BUILD=$BUILD (tag) fallback"
204 fi
205 fi
206 log "Using build number $BUILD"
207}
208
209# ---- Phases ----
210
211phase_deps() {
212 log "Installing build dependencies"
213 # ISP has no IPv6: force apt over IPv4 so it doesn't stall on unreachable IPv6 mirrors.
214 echo 'Acquire::ForceIPv4 "true";' | sudo tee /etc/apt/apt.conf.d/99force-ipv4 >/dev/null
215 sudo apt update
216 sudo apt install -y \
217 yarnpkg zip unzip rsync git gnupg openssh-client scrypt \
218 python3 python-is-python3 diffutils hostname openssl \
219 libfreetype6 fontconfig fonts-dejavu-core \
220 build-essential curl
221 # `repo`: install the official launcher to a WRITABLE location (~/.local/bin) rather than
222 # apt's /usr/bin/repo, which is read-only and makes repo warn it "can't self-update".
223 mkdir -p "$HOME/.local/bin"
224 if [[ ! -x "$HOME/.local/bin/repo" ]]; then
225 curl -fsSL https://storage.googleapis.com/git-repo-downloads/repo -o "$HOME/.local/bin/repo"
226 chmod a+x "$HOME/.local/bin/repo"
227 fi
228 grep -q '.local/bin' ~/.bashrc 2>/dev/null || \
229 echo 'export PATH=$HOME/.local/bin:$PATH' >> ~/.bashrc
230 # AWS CLI v2 (used for R2 uploads). The `awscli` apt package was removed in newer
231 # Ubuntu, so install the official v2 bundle if `aws` isn't already present.
232 if ! command -v aws >/dev/null; then
233 log "Installing AWS CLI v2 from the official bundle"
234 local t; t="$(mktemp -d)"
235 curl -fsSL "https://awscli.amazonaws.com/awscli-exe-linux-$(uname -m).zip" -o "$t/awscliv2.zip"
236 unzip -q "$t/awscliv2.zip" -d "$t"
237 sudo "$t/aws/install" --update
238 rm -rf "$t"
239 fi
240 grep -q '/usr/local/sbin' ~/.bashrc 2>/dev/null || \
241 echo 'export PATH=$PATH:/sbin:/usr/sbin:/usr/local/sbin' >> ~/.bashrc
242 export PATH="$PATH:/sbin:/usr/sbin:/usr/local/sbin"
243 if ! command -v node >/dev/null || [[ "$(node -v 2>/dev/null | cut -c2-3)" -lt 24 ]]; then
244 log "Installing Node.js 24 + yarn (for adevtool)"
245 [[ -s "$HOME/.nvm/nvm.sh" ]] || \
246 curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash
247 . "$HOME/.nvm/nvm.sh"
248 nvm install 24
249 npm install -g yarn
250 fi
251}
252
253# Apply MAOS's patches to GrapheneOS-owned sources. Idempotent: a patch that is already
254# applied is skipped, and one that no longer applies is fatal rather than silent.
255apply_maos_patches() {
256 cd "$TREE"
257 local patches="vendor/modern-apps/patches"
258 [[ -d "$patches" ]] || die "Missing $patches — is vendor/modern-apps synced?"
259 local spec
260 apply_spec() { # apply_spec <repo> <patchfile> — idempotent: skips if already applied
261 local repo="$1" patch="$TREE/$patches/$2"
262 [[ -f "$patch" ]] || die "Missing patch file: $patch"
263 [[ -d "$repo" ]] || die "Missing repo for patch: $repo"
264 if git -C "$repo" apply --reverse --check "$patch" 2>/dev/null; then
265 log "Patch already applied to $repo ($2)"
266 elif git -C "$repo" apply --check "$patch" 2>/dev/null; then
267 git -C "$repo" apply "$patch"
268 log "Applied $2 to $repo"
269 else
270 die "$2 does not apply to $repo. GrapheneOS tag $TAG likely moved these
271 files; rebase the patch (edit $repo, then: git -C $repo diff > $patch)."
272 fi
273 }
274 for spec in "build/make:platform_build.patch" "vendor/adevtool:adevtool.patch" \
275 "vendor/adevtool:adevtool_gnss_servers.patch" \
276 "frameworks/base:frameworks_base.patch" \
277 "frameworks/base:frameworks_base_gnss_servers.patch" \
278 "frameworks/base:frameworks_base_remote_key_provisioning.patch" \
279 "frameworks/base:frameworks_base_widevine_provisioning.patch" \
280 "packages/modules/Connectivity:packages_modules_Connectivity_certificate_transparency.patch" \
281 "frameworks/opt/telephony:frameworks_opt_telephony.patch" \
282 "packages/modules/Permission:permission_roles.patch" \
283 "frameworks/libs/systemui:frameworks_libs_systemui.patch" \
284 "build/release:build_release.patch" \
285 "system/sepolicy:system_sepolicy.patch" \
286 "script:script.patch" \
287 "packages/apps/Settings:settings.patch" \
288 "packages/apps/Settings:packages_apps_Settings_ct_rkp_servers.patch" \
289 "packages/apps/Settings:packages_apps_Settings_widevine_servers.patch" \
290 "packages/apps/Settings:packages_apps_Settings_private_dns_ma_dns.patch" \
291 "packages/apps/Settings:packages_apps_Settings_maos_attestation.patch" \
292 "packages/apps/SetupWizard2:setupwizard2.patch" \
293 "external/roboto-fonts:roboto_fonts.patch" \
294 "packages/apps/GmsCompat:gmscompat.patch" \
295 "packages/modules/NetworkStack:networkstack_captive_portal.patch" \
296 "packages/modules/NetworkStack:networkstack_private_dns_probe.patch"; do
297 apply_spec "${spec%%:*}" "${spec##*:}"
298 done
299 # Per-app Sensors-OPTOUT markers for inherited system apps (one patch per project;
300 # the list keeps this function free of a 60-entry enumeration).
301 local optout_list="$TREE/$patches/sensor-optout.list" repo patch
302 [[ -f "$optout_list" ]] || die "Missing $optout_list"
303 while IFS=: read -r repo patch; do
304 [[ -z "$repo" || "$repo" == \#* ]] && continue
305 apply_spec "$repo" "$patch"
306 done < "$optout_list"
307}
308
309phase_sync() {
310 log "Syncing GrapheneOS $TAG into $TREE"
311 case "$TREE" in /mnt/*) die "TREE is under /mnt (Windows FS). Use ext4, e.g. \$HOME/maos.";; esac
312 # repo requires a git identity for its internal manifest project.
313 git config --global user.name >/dev/null 2>&1 || git config --global user.name "Vayun Mathur"
314 git config --global user.email >/dev/null 2>&1 || \
315 git config --global user.email "[email protected]"
316 # Pre-set color so `repo init` doesn't stop for the interactive color prompt.
317 git config --global color.ui >/dev/null 2>&1 || git config --global color.ui auto
318 mkdir -p "$TREE"; cd "$TREE"
319 repo init -u "$MANIFEST_URL" -b "refs/tags/$TAG"
320
321 # Verify the manifest signature.
322 mkdir -p ~/.ssh && chmod 700 ~/.ssh
323 curl -fsS https://grapheneos.org/allowed_signers > ~/.ssh/grapheneos_allowed_signers
324 ( cd .repo/manifests
325 git config gpg.ssh.allowedSignersFile ~/.ssh/grapheneos_allowed_signers
326 git verify-tag "$(git describe)" ) || die "Manifest tag verification failed."
327
328 # Inject the MAOS overlay via a local manifest (no fork of platform_manifest).
329 mkdir -p .repo/local_manifests
330 cat > .repo/local_manifests/modern-apps.xml <<EOF
331<?xml version="1.0" encoding="UTF-8"?>
332<manifest>
333 <remote name="maos-github" fetch="$MAOS_GH" />
334 <project path="vendor/modern-apps" name="MAOS" remote="maos-github" revision="main" />
335</manifest>
336EOF
337 log "repo sync (this downloads ~150 GB; resumable)"
338 repo sync -j8
339 # repo sync is exactly what reverts these, so re-apply right after.
340 apply_maos_patches
341}
342
343populate_prebuilts() {
344 cd "$TREE"
345 local dest="vendor/modern-apps/prebuilts"; mkdir -p "$dest"
346 # The Modern Apps APKs are device-independent, so only populate them once: skip if every
347 # APK is already present and non-empty (this makes it a no-op on every device after the
348 # first in a multi-device run instead of re-downloading all of them each time).
349 local missing=0 app
350 for app in "${APPS[@]}"; do [[ -s "$dest/$app-release.apk" ]] || { missing=1; break; }; done
351 if [[ "$missing" -eq 0 ]]; then
352 log "Modern Apps prebuilt APKs already present — skipping."
353 return 0
354 fi
355 log "Populating Modern Apps prebuilt APKs"
356 if [[ -n "$MODERN_APPS_SRC" ]]; then
357 vendor/modern-apps/scripts/collect-apks.sh "$MODERN_APPS_SRC"
358 else
359 warn "MODERN_APPS_SRC unset - downloading APKs from the $MODERN_APPS_GH latest release."
360 for app in "${APPS[@]}"; do
361 curl -fL -o "$dest/$app-release.apk" \
362 "https://github.com/$MODERN_APPS_GH/releases/latest/download/$app-release.apk" \
363 || die "Could not download $app-release.apk"
364 done
365 fi
366}
367
368phase_vendor() {
369 # Must precede generate-all: the eSIM removal lives in adevtool's vendor
370 # skeletons, which are the source this copies into vendor/google_devices/.
371 apply_maos_patches
372 log "Extracting Pixel vendor files for $DEVICE (adevtool)"
373 cd "$TREE"; source build/envsetup.sh
374 # Modern Apps prebuilt APKs must exist before adevtool generate-all triggers a
375 # soong build that parses vendor/modern-apps/Android.bp (globs prebuilts/*-release.apk).
376 populate_prebuilts
377 # adevtool's node deps are device-independent; install them once (skip if already present).
378 [[ -d vendor/adevtool/node_modules ]] || yarn --cwd vendor/adevtool/ install
379 # adevtool is an oclif CLI — its launcher is vendor/adevtool/bin/run (there is no global
380 # `adevtool` command, and `yarn run adevtool` has no such script). Prefer bin/run, with
381 # fallbacks for older layouts / a PATH install.
382 local ADEV
383 if [[ -x vendor/adevtool/bin/run ]]; then ADEV=(vendor/adevtool/bin/run)
384 elif [[ -x vendor/adevtool/bin/adevtool ]]; then ADEV=(vendor/adevtool/bin/adevtool)
385 elif command -v adevtool >/dev/null; then ADEV=(adevtool)
386 else die "adevtool launcher not found under vendor/adevtool/bin (did 'yarn install' succeed?)"
387 fi
388 "${ADEV[@]}" generate-all -d "$DEVICE"
389}
390
391phase_overlay() {
392 cd "$TREE"
393
394 # Modern Apps prebuilt APKs are populated in phase_vendor (populate_prebuilts),
395 # before adevtool runs soong; nothing to do here.
396
397 log "Verifying stock module names against this tag"
398 grep -rn --include=*.mk -e '\bCamera\b' -e '\bPdfViewer\b' -e '\bApps\b' \
399 -e '\bContacts\b' -e '\bDeskClock\b' -e 'Calculator' -e 'Gallery2' -e 'DocumentsUI' \
400 -e '\bDialer\b' -e '\bMessaging\b' -e '\bEuiccGoogle\b' \
401 -e '\bSeedvault\b' -e '\bContactsBackup\b' \
402 -e '\bEmergencyInfo\b' \
403 build/ device/ vendor/ | grep -i 'PRODUCT_PACKAGES' || true
404 warn "Confirm the names above match the filter-out list in vendor/modern-apps/modern_apps.mk."
405
406 log "Wiring MAOS product config into the $DEVICE makefile"
407 # GrapheneOS generates the device product makefile under vendor/google_devices/<dev>/
408 # (there is no device/google/<family> product tree); prefer that, then fall back to
409 # older device/google layouts.
410 local mk="" _cand
411 for _cand in \
412 "vendor/google_devices/${DEVICE}/${DEVICE}.mk" \
413 "$(find device/google -name "aosp_${DEVICE}.mk" 2>/dev/null | head -1)" \
414 "$(find device/google -name "*${DEVICE}*.mk" 2>/dev/null | head -1)"; do
415 if [[ -n "$_cand" && -f "$_cand" ]]; then mk="$_cand"; break; fi
416 done
417 [[ -n "$mk" ]] || die "Could not find the product makefile for $DEVICE."
418 if ! grep -q 'vendor/modern-apps/modern_apps.mk' "$mk"; then
419 printf '\n$(call inherit-product, vendor/modern-apps/modern_apps.mk)\n' >> "$mk"
420 log "Appended MAOS inherit to $mk"
421 else
422 log "MAOS inherit already present in $mk"
423 fi
424
425 # No Updater URL wiring here: the MA Updater app (ModernAppsUpdater, which
426 # overrides the GrapheneOS Updater in Android.bp) reads ro.maos.ota.server
427 # from maos_branding.mk. The GrapheneOS Updater is displaced, not configured.
428}
429
430phase_keys() {
431 require_passphrase
432 if [[ -f "$MAOS_KEYS_FILE" ]]; then
433 log "Key file already exists ($MAOS_KEYS_FILE) — skipping generation."
434 return 0
435 fi
436 log "Generating signing keys (into RAM, then encrypting to $MAOS_KEYS_FILE)"
437 cd "$TREE"; source build/envsetup.sh
438 rm -rf "$KEYS_PLAIN"; mkdir -p "$KEYS_PLAIN"; chmod 700 "$KEYS_PLAIN"
439 local CN="MAOS"
440 for k in releasekey platform shared media networkstack bluetooth sdk_sandbox gmscompat_lib nfc; do
441 # AOSP make_key always exits 1 via its EXIT trap even on success; ignore its exit
442 # status and verify the generated artifacts instead.
443 echo | development/tools/make_key "$KEYS_PLAIN/$k" "/CN=$CN/" || true
444 [[ -s "$KEYS_PLAIN/$k.pk8" && -s "$KEYS_PLAIN/$k.x509.pem" ]] || die "make_key $k failed"
445 done
446 # AVB key must be an unencrypted RSA PEM: avbtool reads it non-interactively, and
447 # an encrypted key makes load_public_key() fall through to ML-DSA (unsupported by
448 # the system openssl). The whole key set is scrypt-encrypted later into MAOS_KEYS_FILE.
449 openssl genrsa -out "$KEYS_PLAIN/avb.pem" 4096
450 external/avb/avbtool.py extract_public_key --key "$KEYS_PLAIN/avb.pem" \
451 --output "$KEYS_PLAIN/avb_pkmd.bin"
452 ssh-keygen -t ed25519 -N "" -f "$KEYS_PLAIN/id_ed25519" >/dev/null
453
454 mkdir -p "$(dirname "$MAOS_KEYS_FILE")"
455 rm -f "$KEYS_TAR"
456 tar czf "$KEYS_TAR" -C "$KEYS_PLAIN" .
457 scrypt_enc "$KEYS_TAR" "$MAOS_KEYS_FILE"
458 shred -u "$KEYS_TAR" 2>/dev/null || rm -f "$KEYS_TAR"
459 chmod 600 "$MAOS_KEYS_FILE"
460 log "Encrypted key set (scrypt) written to $MAOS_KEYS_FILE — back it up; losing it bricks OTA."
461}
462
463phase_build() {
464 log "Building MAOS for $DEVICE (tag $TAG, build $BUILD)"
465 cd "$TREE"; source build/envsetup.sh
466 export OFFICIAL_BUILD=true
467 # Build variant for lunch <device>-cur-<variant>. Defaults to the shippable
468 # `user` variant; set MAOS_BUILD_VARIANT=userdebug explicitly for debugging
469 # (adbd as root from init, disabled-verity-tolerant logging).
470 VARIANT="${MAOS_BUILD_VARIANT:-user}"
471 # Build in the DEFAULT out/. soong's siso/product config is anchored to it (a custom
472 # OUT_DIR breaks '@config//main.star' loading during bootstrap), so builds run one at a
473 # time. No rm -rf here: builds are incremental and reuse out/; wipe it manually
474 # when you want a clean build (GrapheneOS does rm -rf between devices).
475 lunch "${DEVICE}-cur-${VARIANT}"
476 # Pixel 6 (Tensor G1: bluejay/raven/oriole) has no separate vendor_kernel_boot image;
477 # every device since the Pixel 6a does. Building vendorkernelbootimage for a Pixel 6 fails.
478 local boot_targets="vendorbootimage vendorkernelbootimage"
479 case "$DEVICE" in bluejay|raven|oriole) boot_targets="vendorbootimage" ;; esac
480 # BUILD_NUMBER is pinned by the dispatch (pin_build_number); soong honors it so artifacts
481 # match. Build device images, target-files AND otatools in one graph pass.
482 export BUILD_NUMBER="$BUILD"
483 m $boot_targets target-files-package otatools-package
484 # Stage <device>-target_files.zip + <device>-otatools.zip into releases/<build>/ so the
485 # release phase runs decoupled from out/ (hence in parallel across devices). finalize.sh
486 # reads BUILD_NUMBER/OUT/ANDROID_HOST_OUT/TARGET_PRODUCT from the lunch'd env.
487 script/finalize.sh
488 log "Staged target_files + otatools for $DEVICE into releases/$BUILD/"
489}
490
491phase_release() {
492 # Decoupled from out/: generate-release.sh works entirely from the staged
493 # releases/<build>/<device>-{target_files,otatools}.zip, so this can run in parallel across
494 # devices. Keys are unlocked into RAM + symlinked as keys/<device> by the dispatch before
495 # the release pass (so parallel jobs don't race on decryption); the fallback below covers a
496 # standalone `release` invocation.
497 log "Signing + generating factory image and full OTA for $DEVICE (build $BUILD)"
498 cd "$TREE"
499 if [[ ! -L "$TREE/keys/$DEVICE" ]]; then
500 unlock_keys_shared
501 link_keys "$DEVICE"
502 fi
503 # GrapheneOS's script/decrypt-keys (invoked by generate-release.sh) prompts for the
504 # passphrase the per-key .pk8/avb.pem are encrypted with. build-maos.sh keeps the individual
505 # keys UNENCRYPTED inside the scrypt blob (already unlocked into RAM), so that passphrase is
506 # empty. Predefine it so decrypt-keys runs non-interactively and takes the plaintext path
507 # instead of trying to decrypt an already-plaintext key (openssl "asn1 wrong tag" error).
508 export password=""
509 # MAOS_SKIP_OTA=1 skips the OTA zip for faster flash-test releases
510 # (see script.patch). Publish path always builds the OTA.
511 if [[ -n "${MAOS_SKIP_OTA:-}" ]]; then export SKIP_OTA=1; fi
512 script/generate-release.sh "$DEVICE" "$BUILD"
513 log "Release at releases/$BUILD/release-$DEVICE-$BUILD"
514}
515
516phase_publish() {
517 : "${R2_ACCOUNT_ID:?set R2_ACCOUNT_ID}"; : "${R2_ACCESS_KEY_ID:?}"; : "${R2_SECRET_ACCESS_KEY:?}"
518 cd "$TREE"
519 resolve_build_number
520 local rel="releases/$BUILD/release-$DEVICE-$BUILD"
521 [[ -d "$rel" ]] || die "Release dir $rel not found — run the 'release' phase first."
522
523 export AWS_ACCESS_KEY_ID="$R2_ACCESS_KEY_ID" AWS_SECRET_ACCESS_KEY="$R2_SECRET_ACCESS_KEY"
524 export AWS_DEFAULT_REGION=auto
525 export AWS_REQUEST_CHECKSUM_CALCULATION=when_required
526 export AWS_RESPONSE_CHECKSUM_VALIDATION=when_required
527 local EP="https://$R2_ACCOUNT_ID.r2.cloudflarestorage.com"
528 r2() { aws s3 --endpoint-url "$EP" "$@"; }
529
530 log "Publishing OTA (zip first, channel metadata last)"
531 r2 cp "$rel/$DEVICE-ota_update-$BUILD.zip" "s3://$R2_BUCKET/" \
532 --content-type application/zip --cache-control 'public, max-age=31536000, immutable' \
533 --only-show-errors
534 r2 cp "$rel/$DEVICE-$OTA_CHANNEL" "s3://$R2_BUCKET/" \
535 --content-type 'text/plain; charset=utf-8' --cache-control 'no-store, must-revalidate' \
536 --only-show-errors
537
538 log "Publishing factory image for the web installer"
539 # The web installer consumes the *install* zip (contains super_1..N.img already split to
540 # the device max-download-size, plus script.txt — GrapheneOS's verified flash sequence).
541 # prepare-factory.sh translates that script.txt into the ordered installer manifest.
542 R2_BUCKET="$R2_BUCKET" vendor/modern-apps/installer/prepare-factory.sh \
543 -d "$DEVICE" -b "$BUILD" -f "$rel/$DEVICE-install-$BUILD.zip" \
544 || warn "prepare-factory.sh failed — see its output. For a factory-zip fallback pass -P \
545plan.json mirroring flash-all (incl. flashing avb_custom_key before lock)."
546 log "Done. OTA: https://ota.maproj.org/$DEVICE-$OTA_CHANNEL"
547}
548
549# ---- Dispatch ----
550# Generic fan-out: run <fn> for each device arg, up to <jobs> at once, each in its own
551# subshell + per-device log; append succeeded devices to the named array (<resultvar>). Used
552# for build/release/publish. set -e inside each job aborts just that device; the EXIT
553# key-wipe trap is reset inside subshells so it never fires mid-run.
554run_parallel() { # run_parallel <label> <fn> <jobs> <resultvar> <device...>
555 local label="$1" fn="$2" jobs="$3"; local -n __ok_ref="$4"; shift 4
556 local logdir="$TREE/releases/$BUILD/logs"; mkdir -p "$logdir"
557 log "$label: $# device(s), up to $jobs at a time; per-device logs in $logdir"
558 local -a bpids=() bdevs=(); local dev i
559 for dev in "$@"; do
560 ( set -e; DEVICE="$dev"; "$fn" ) >"$logdir/$label-$dev.log" 2>&1 &
561 bpids+=("$!"); bdevs+=("$dev")
562 log "$label[$dev] started (pid $!) -> $logdir/$label-$dev.log"
563 if (( ${#bpids[@]} >= jobs )); then
564 for i in "${!bpids[@]}"; do
565 if wait "${bpids[$i]}"; then log "$label[${bdevs[$i]}] OK"; __ok_ref+=("${bdevs[$i]}")
566 else warn "$label[${bdevs[$i]}] FAILED — see $logdir/$label-${bdevs[$i]}.log"; fi
567 done
568 bpids=(); bdevs=()
569 fi
570 done
571 if (( ${#bpids[@]} > 0 )); then
572 for i in "${!bpids[@]}"; do
573 if wait "${bpids[$i]}"; then log "$label[${bdevs[$i]}] OK"; __ok_ref+=("${bdevs[$i]}")
574 else warn "$label[${bdevs[$i]}] FAILED — see $logdir/$label-${bdevs[$i]}.log"; fi
575 done
576 fi
577}
578
579# Copy a (possibly empty) array safely under `set -u`: copy_arr <destvar> <srcvar>
580copy_arr() { local -n __d="$1"; local -n __s="$2"; __d=(); (( ${#__s[@]} > 0 )) && __d=("${__s[@]}"); return 0; }
581
582[[ $# -gt 0 ]] || { echo "usage: $0 [-d DEVICE] [-t TAG] [-c CHANNEL] <phase...> (phases: deps sync vendor overlay keys build release publish all; -d accepts a codename, 'all', or a comma-separated subset)"; exit 2; }
583
584# Parse requested phases into booleans; the passes below enforce canonical order and the
585# once / sequential-prep / parallel-build / parallel-release / parallel-publish structure.
586want_deps=false; want_sync=false; want_keys=false
587want_vendor=false; want_overlay=false; want_build=false; want_release=false; want_publish=false
588for p in "$@"; do
589 case "$p" in
590 all) want_deps=true; want_sync=true; want_keys=true
591 want_vendor=true; want_overlay=true; want_build=true; want_release=true; want_publish=true ;;
592 deps) want_deps=true ;;
593 sync) want_sync=true ;;
594 keys) want_keys=true ;;
595 vendor) want_vendor=true ;;
596 overlay) want_overlay=true ;;
597 build) want_build=true ;;
598 release) want_release=true ;;
599 publish) want_publish=true ;;
600 *) die "Unknown phase '$p'. Use: deps sync vendor overlay keys build release publish all" ;;
601 esac
602done
603
604log "MAOS build — devices=[${DEVICES_LIST[*]}] tag=$TAG channel=$OTA_CHANNEL tree=$TREE bucket=$R2_BUCKET"
605
606# ---- Pass 1: device-independent phases, once ----
607if $want_deps; then phase_deps; fi
608if $want_sync; then phase_sync; fi
609if $want_keys; then phase_keys; fi
610
611# Pin the batch build number up front (so prep logs, all out-<device>/ builds, release and
612# publish share one releases/<build>/ dir) when we're going to build.
613if $want_build; then pin_build_number; fi
614
615# ---- Pass 2a: prep (vendor + overlay), per device, SEQUENTIAL ----
616# These write shared parts of the source tree (adevtool's internal build, the shared Updater
617# config.xml), so they must not run concurrently. Builds afterward only read the tree. We run
618# them via run_parallel with jobs=1 (not `if ( set -e; ... )`, which would DISABLE the inner
619# set -e — bash ignores errexit for a subshell used as an if-condition — and hide a
620# phase_vendor failure behind a later phase_overlay success).
621_prep_one() {
622 if $want_vendor; then phase_vendor; fi
623 if $want_overlay; then phase_overlay; fi
624}
625PREP_OK=()
626did_prep=false
627if $want_vendor || $want_overlay; then did_prep=true; fi
628if $did_prep; then
629 run_parallel prep _prep_one 1 PREP_OK "${DEVICES_LIST[@]}"
630else
631 copy_arr PREP_OK DEVICES_LIST
632fi
633
634# ---- Pass 2b: build, per device, SEQUENTIAL (default out/; live output) ----
635# soong's siso/product config is anchored to the default out/ dir, so we can't give each
636# device its own out/ in one checkout (a custom OUT_DIR breaks '@config//main.star' at soong
637# bootstrap). Builds therefore run one at a time with full cores; release/publish still fan
638# out in parallel below. Each build runs in a backgrounded subshell + wait so set -e is
639# honored inside (an `if ( set -e; … )` condition would DISABLE it) while output still
640# streams live to the terminal.
641BUILT_OK=()
642if $want_build; then
643 blddevs=(); copy_arr blddevs PREP_OK
644 if (( ${#blddevs[@]} == 0 )); then warn "No devices available to build."; fi
645 for dev in ${blddevs[@]+"${blddevs[@]}"}; do
646 log "=== Build $dev ==="
647 ( set -e; DEVICE="$dev"; phase_build ) &
648 if wait $!; then BUILT_OK+=("$dev")
649 else warn "Device $dev FAILED during build — skipping its release/publish."; fi
650 done
651else
652 copy_arr BUILT_OK PREP_OK
653fi
654
655# ---- Pass 3: release, across devices, IN PARALLEL ----
656RELEASED_OK=()
657if $want_release; then
658 resolve_build_number # pin BUILD for all parallel release jobs
659 reldevs=(); copy_arr reldevs BUILT_OK
660 if (( ${#reldevs[@]} == 0 )); then warn "No devices available to release."
661 else
662 unlock_keys_shared # decrypt once; each job just reads keys/<device>
663 for dev in "${reldevs[@]}"; do link_keys "$dev"; done
664 export password=""
665 run_parallel release phase_release "${MAOS_RELEASE_JOBS:-4}" RELEASED_OK "${reldevs[@]}"
666 fi
667else
668 copy_arr RELEASED_OK BUILT_OK
669fi
670
671# ---- Pass 4: publish, across devices, IN PARALLEL ----
672PUBLISHED_OK=()
673if $want_publish; then
674 resolve_build_number
675 pubdevs=(); copy_arr pubdevs RELEASED_OK
676 if (( ${#pubdevs[@]} == 0 )); then warn "No devices available to publish."
677 else run_parallel publish phase_publish "${MAOS_PUBLISH_JOBS:-4}" PUBLISHED_OK "${pubdevs[@]}"; fi
678fi
679
680# ---- Summary ----
681if $did_prep || $want_build || $want_release || $want_publish; then
682 success=()
683 if $want_publish; then copy_arr success PUBLISHED_OK; laststage=publish
684 elif $want_release; then copy_arr success RELEASED_OK; laststage=release
685 elif $want_build; then copy_arr success BUILT_OK; laststage=build
686 else copy_arr success PREP_OK; laststage=prep
687 fi
688 declare -A _ok=()
689 for d in ${success[@]+"${success[@]}"}; do _ok[$d]=1; done
690 log "Per-device summary through '$laststage' (${#DEVICES_LIST[@]} device(s)):"
691 any_fail=false
692 for d in "${DEVICES_LIST[@]}"; do
693 if [[ -n "${_ok[$d]:-}" ]]; then printf ' %s: OK\n' "$d"
694 else printf ' %s: FAILED\n' "$d"; any_fail=true; fi
695 done
696 if $any_fail; then log "Requested phases complete (with failures)."; exit 1; fi
697fi
698
699log "All requested phases complete."