Cotton code
273 lines · 13.9 KB · ShellRaw
#!/usr/bin/env bash# Cotton's apps on Android (apps/android: one shared shell, one product flavour# per registry app), built as Play takes them or as a walk installs them.##   pnpm android:bundle --flavor <app>|<app>-dev [--unsigned]#       the signed Android App Bundle (bundle<App><Live|Dev>Release): prints#       its path, size and build number, and verifies its signature. With#       --unsigned (the box's cut, `pnpm android:release`): the same bundle#       with no signature and no upload key looked for or read, checked to#       carry none; the signing machine signs it#   pnpm android:apk --flavor <app>|<app>-dev [--release]#       the APK an emulator walk installs: debug (assemble<App><Live|Dev>Debug),#       or with --release the R8-shrunk release APK signed with the upload key## <app> is a registry slug whose android.project is apps/android (books,# cinemas, …): the registry is read, never a list here.## THE BUILD NUMBER (versionCode) Play counts by, and refuses once it has seen# it, is the commit's place on main: `git rev-list --count --first-parent HEAD`# (9,306 on 15 Nov 2026). Main is never force-pushed, so it only grows; a re-cut# of the same commit gets the same number and Play refuses it, as it should.# Nothing is written back and there is no file to commit (the counter file a# bundle bumped, apps/android/version-code/, is gone: a bump that never landed# left main behind Play, 15 Nov 2026). A bundle is cut only from a commit# origin/main holds (a lane's own commit would spend a number main reaches later# at another commit) and never from a shallow clone (its count is short). Gradle# counts the same way when run alone (app/build.gradle.kts). versionName stays 1.0.0.## `<app>` is the live Worker (https://cottondb.com), `<app>-dev` the dev one;# their application ids differ (`.dev`), so both install side by side.## THE UPLOAD KEY lives outside the tree, one per Play app. The build reads# COTTON_ANDROID_KEYSTORE (the keystore's path), COTTON_ANDROID_KEYSTORE_PASSWORD_FILE# (a file holding its one password) and COTTON_ANDROID_KEY_ALIAS (default# <app>-upload); where the first two are unset and this Mac holds the upload# key at ~/.cotton-credentials/google/<app>-upload.{jks,password}, those are# named. Anything still missing is said by name and nothing is built. The# password is never read here: Gradle reads the file.## THE CORE is the Rust .so built for Android on the box (cargo-ndk). A debug# APK carries the one whole core every app shares, the android-debug profile's,# from apps/android/app/src/debug/jniLibs/arm64-v8a/. A release carries the# app's OWN core, the android profile's built for its kit (`pnpm android:core# <app>`: its kit's pictures and the shell's, no other app's), from# app/src/release-<app>/jniLibs/arm64-v8a/, with the kit it was built for# beside it (core-kit); a core built for another kit is refused. Without its# core nothing is built (the APK would open to nothing).## Overrides: COTTON_ANDROID_DIR (the Gradle project, for the test),# COTTON_ANDROID_REGISTRY (the registry, for the test), COTTON_ANDROID_BUILD_ROOT# (build output outside the checkout, as a lane keeps it), JAVA_HOME (else# java_home -v 17, else the box's /usr/lib/jvm/java-17-openjdk-amd64),# ANDROID_HOME (else ~/Library/Android/sdk, else the box's /opt/android-sdk).set -euo pipefailROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"PROJECT="${COTTON_ANDROID_DIR:-$ROOT/apps/android}"REGISTRY="${COTTON_ANDROID_REGISTRY:-$ROOT/apps/registry.json}"usage() {  echo "usage: android-bundle.sh bundle --flavor <app>|<app>-dev [--unsigned]" >&2  echo "       android-bundle.sh apk --flavor <app>|<app>-dev [--release]" >&2  exit 2}[ $# -ge 1 ] || usagewhat="$1"shiftcase "$what" in  bundle | apk) ;;  *) usage ;;esacflavor=""release=0unsigned=0while [ $# -gt 0 ]; do  case "$1" in    --flavor)      [ $# -ge 2 ] || { echo "android-bundle: --flavor needs an app (books, books-dev, cinemas, …)" >&2; exit 2; }      flavor="$2"      shift 2      ;;    --flavor=*) flavor="${1#--flavor=}"; shift ;;    --release) release=1; shift ;;    --unsigned) unsigned=1; shift ;;    *) echo "android-bundle: unknown argument '$1'" >&2; usage ;;  esacdone# The registry's Android apps (android.project apps/android), and the Gradle# product flavours each name builds: <app> × live, or <app> × dev.apps="$(node -e '  const apps = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8")).apps;  for (const app of apps) if (app.android && app.android.project === "apps/android") console.log(app.slug);' "$REGISTRY")"[ -n "$apps" ] || { echo "android-bundle: $REGISTRY names no app built from apps/android" >&2; exit 1; }named="$(printf '%s\n' "$apps" | sed 's/$/, /' | tr -d '\n' | sed 's/, $//')"if [ -z "$flavor" ]; then  echo "android-bundle: say which app: --flavor <app> (live) or --flavor <app>-dev (dev Worker), <app> one of: $named" >&2  exit 2fiapp="${flavor%-dev}"if [ "$app" = "$flavor" ]; then server=Live; else server=Dev; fiprintf '%s\n' "$apps" | grep -qx "$app" || { echo "android-bundle: no flavor '$flavor' (one of: $named, each also as <app>-dev)" >&2; exit 2; }App="$(printf '%s' "${app:0:1}" | tr '[:lower:]' '[:upper:]')${app:1}"variant="$App$server"product="$app$server"lower_server="$(printf '%s' "$server" | tr '[:upper:]' '[:lower:]')"if [ "$what" = bundle ] && [ "$release" = 1 ]; then  echo "android-bundle: a bundle is always a release; --release is for apk" >&2  exit 2fiif [ "$unsigned" = 1 ] && [ "$what" != bundle ]; then  echo "android-bundle: --unsigned is for a bundle (the build box's cut the signing Mac signs); an APK is debug or signed" >&2  exit 2fi# The build number: this commit's place on main's first-parent line.[ "$(git -C "$PROJECT" rev-parse --is-shallow-repository 2>/dev/null)" = false ] || {  echo "android-bundle: $PROJECT is not in a whole git clone (shallow, or none): the build number is the commit count on main, which a shallow clone gets wrong" >&2  exit 1}if [ "$what" = bundle ]; then  git -C "$PROJECT" merge-base --is-ancestor HEAD refs/remotes/origin/main 2>/dev/null || {    echo "android-bundle: HEAD ($(git -C "$PROJECT" rev-parse --short HEAD)) is not on origin/main: a bundle is cut from main (push, fetch, and cut again), or its build number is one main reaches later at another commit" >&2    exit 1  }fibuild="$(git -C "$PROJECT" rev-list --count --first-parent HEAD)"export COTTON_ANDROID_VERSION_CODE="$build"# A release (a bundle, or apk --release) carries the app's own `android`# profile core from src/release-<app>/jniLibs, a debug APK the one# `android-debug` core from src/debug/jniLibs (app/build.gradle.kts): the two# never swap, and no app ships another's.if [ "$what" = bundle ] || [ "$release" = 1 ]; then  home="$PROJECT/app/src/release-$app"  library="$home/jniLibs/arm64-v8a/libcotton_android_jni.so"  [ -s "$library" ] || {    echo "android-bundle: no core at $library — build $app's own with: pnpm android:core $app (cotton-android-jni for arm64-v8a at --profile android, its kit's pictures)" >&2    exit 1  }  kit="$(python3 "$ROOT/scripts/lib/registry.py" app-core-kit "$REGISTRY" "$app")" || exit 1  [ -f "$home/core-kit" ] || { echo "android-bundle: $home/core-kit does not say which kit that core was built for — build it with: pnpm android:core $app" >&2; exit 1; }  built="$(tr -d ' \t\r\n' < "$home/core-kit")"  [ "$built" = "$kit" ] || {    echo "android-bundle: the core at $library was built for kit '${built}', and $app's kit is '${kit}': it carries another app's pictures — build $app's own with: pnpm android:core $app" >&2    exit 1  }else  library="$PROJECT/app/src/debug/jniLibs/arm64-v8a/libcotton_android_jni.so"  [ -s "$library" ] || {    echo "android-bundle: no core at $library — build cotton-android-jni for arm64-v8a on the box (cargo ndk … build --profile android-debug) and copy target/aarch64-linux-android/android-debug/libcotton_android_jni.so there first" >&2    exit 1  }fisigned=0gradle_props=()if [ "$unsigned" = 1 ]; then  # No upload key is ever on the box: none is looked for, and any named is not handed to Gradle.  unset COTTON_ANDROID_KEYSTORE COTTON_ANDROID_KEYSTORE_PASSWORD_FILE COTTON_ANDROID_KEY_ALIAS  gradle_props=(-Pcotton.unsignedRelease=true)elif [ "$what" = bundle ] || [ "$release" = 1 ]; then  signed=1  credentials="$HOME/.cotton-credentials/google"  if [ -z "${COTTON_ANDROID_KEYSTORE:-}" ] && [ -f "$credentials/$app-upload.jks" ]; then    export COTTON_ANDROID_KEYSTORE="$credentials/$app-upload.jks"  fi  if [ -z "${COTTON_ANDROID_KEYSTORE_PASSWORD_FILE:-}" ] && [ -f "$credentials/$app-upload.password" ]; then    export COTTON_ANDROID_KEYSTORE_PASSWORD_FILE="$credentials/$app-upload.password"  fi  export COTTON_ANDROID_KEY_ALIAS="${COTTON_ANDROID_KEY_ALIAS:-$app-upload}"  for name in COTTON_ANDROID_KEYSTORE COTTON_ANDROID_KEYSTORE_PASSWORD_FILE; do    value="${!name:-}"    [ -n "$value" ] || { echo "android-bundle: $name is not set: a release is signed with the upload key, kept outside the tree" >&2; exit 1; }    [ -f "$value" ] || { echo "android-bundle: $name names no file: $value" >&2; exit 1; }  donefiif [ -z "${JAVA_HOME:-}" ]; then  JAVA_HOME="$(/usr/libexec/java_home -v 17 2>/dev/null)" || JAVA_HOME=""  if [ -z "$JAVA_HOME" ] && [ -x /usr/lib/jvm/java-17-openjdk-amd64/bin/java ]; then JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64; fi  [ -n "$JAVA_HOME" ] || { echo "android-bundle: no JDK 17 (set JAVA_HOME)" >&2; exit 1; }fiexport JAVA_HOMEif [ -z "${ANDROID_HOME:-}" ]; then  if [ -d "$HOME/Library/Android/sdk" ]; then ANDROID_HOME="$HOME/Library/Android/sdk"; else ANDROID_HOME=/opt/android-sdk; fifiexport ANDROID_HOME# Gradle's build directory is app/build inside the checkout, or <root>/app when# COTTON_ANDROID_BUILD_ROOT moves it out (build.gradle.kts).if [ -n "${COTTON_ANDROID_BUILD_ROOT:-}" ]; then  outputs="$COTTON_ANDROID_BUILD_ROOT/app/outputs"else  outputs="$PROJECT/app/build/outputs"fiif [ "$what" = bundle ]; then  task=":app:bundle${variant}Release"  product_path="$outputs/bundle/${product}Release/app-${app}-${lower_server}-release.aab"elif [ "$release" = 1 ]; then  task=":app:assemble${variant}Release"  product_path="$outputs/apk/${product}/release/app-${app}-${lower_server}-release.apk"else  task=":app:assemble${variant}Debug"  product_path="$outputs/apk/${product}/debug/app-${app}-${lower_server}-debug.apk"fiecho "[android] $task" >&2rm -f "$product_path"(cd "$PROJECT" && ./gradlew -q ${gradle_props[@]+"${gradle_props[@]}"} "$task")[ -f "$product_path" ] || { echo "android-bundle: Gradle wrote no $product_path" >&2; exit 1; }# 16 KB PAGES (LAUNCH.md, 22 Nov 2026): what Play takes carries only 64-bit libraries aligned to 16 KB pages# (Play refuses an update without, from 1 Feb 2027): read where AGP merged this variant's libraries.if [ "$what" = bundle ] || [ "$release" = 1 ]; then  if [ -n "${COTTON_ANDROID_BUILD_ROOT:-}" ]; then merged="$COTTON_ANDROID_BUILD_ROOT/app/intermediates/merged_native_libs/${product}Release"; else merged="$PROJECT/app/build/intermediates/merged_native_libs/${product}Release"; fi  # Each arm64-v8a and x86_64 library: every LOAD program header's p_align at least 2**14 (a 64-bit little-endian ELF).  u() { od -An -t "u$3" -j "$2" -N "$3" "$1" | tr -d ' '; }  libs=0; short=""  while IFS= read -r so; do    libs=$((libs + 1))    if [ "$(od -An -t x1 -N 6 "$so" | tr -d ' ')" != 7f454c460201 ]; then short="$short\n  ${so#"$merged"/}: not a 64-bit ELF"; continue; fi    phoff="$(u "$so" 32 8)"; size="$(u "$so" 54 2)"; count="$(u "$so" 56 2)"; i=0; loads=0    while [ "$i" -lt "$count" ]; do      at=$((phoff + i * size))      if [ "$(u "$so" "$at" 4)" = 1 ]; then        loads=$((loads + 1)); align="$(u "$so" $((at + 48)) 8)"        [ "$align" -ge 16384 ] || short="$short\n  ${so#"$merged"/}: LOAD aligned to $align bytes, under 16384"      fi      i=$((i + 1))    done    [ "$loads" -gt 0 ] || short="$short\n  ${so#"$merged"/}: no LOAD segment"  done < <(find "$merged" -name '*.so' \( -path '*/arm64-v8a/*' -o -path '*/x86_64/*' \) 2>/dev/null | sort)  [ "$libs" -gt 0 ] || { echo "android-bundle: no arm64-v8a or x86_64 library under $merged: every app carries its core" >&2; exit 1; }  if [ -n "$short" ]; then printf "android-bundle: %s is not for Play: Play refuses these for Android 15 and later (16 KB pages):%b\n" "$product_path" "$short" >&2; exit 1; fi  echo "16 KB pages: $libs libraries aligned" >&2fibytes="$(wc -c < "$product_path" | tr -d ' ')"printf '%s\n' "$product_path"awk -v bytes="$bytes" 'BEGIN { printf "%d bytes (%.1f MB)\n", bytes, bytes / 1000000 }'if [ "$unsigned" = 1 ]; then  # The box's cut carries no signature at all: one found means a key reached this build.  verified="$("$JAVA_HOME/bin/jarsigner" -verify "$product_path" 2>&1)" || true  case "$verified" in    *"jar is unsigned"*) echo "unsigned (no upload key on this machine; the signing machine signs it)" ;;    *) echo "android-bundle: $product_path should carry no signature, and jarsigner says:" >&2; printf '%s\n' "$verified" >&2; exit 1 ;;  esacfiif [ "$signed" = 1 ]; then  # A bundle carries a jar signature (jarsigner verifies it); an APK for  # minSdk 28 carries only the v2/v3 scheme, which apksigner verifies. An  # unsigned or tampered product fails here, not at Play.  if [ "$what" = bundle ]; then    verified="$("$JAVA_HOME/bin/jarsigner" -verify "$product_path" 2>&1)" && case "$verified" in *"jar verified."*) ;; *) false ;; esac  else    apksigner="$(ls -d "$ANDROID_HOME"/build-tools/*/apksigner 2>/dev/null | sort -V | tail -n 1)"    [ -n "$apksigner" ] || { echo "android-bundle: no apksigner under $ANDROID_HOME/build-tools" >&2; exit 1; }    verified="$("$apksigner" verify "$product_path" 2>&1)"  fi || {    echo "android-bundle: $product_path is not signed as it should be:" >&2    printf '%s\n' "$verified" >&2    exit 1  }  echo "signature verified (upload key)"fiecho "versionCode $build (versionName 1.0.0), commit $(git -C "$PROJECT" rev-parse --short HEAD)'s place on main"