#!/usr/bin/env bash
#
# build-patched-apk.sh
#
# Builds a patched Element X Android APK that fixes the DM room selection bug
# where searching for a user and tapping them could open a group DM instead
# of a 1:1 DM.
#
# Usage:
#   ./build-patched-apk.sh
#
# Output:
#   APKs are copied to ./output/ in the current directory.
#   The arm64-v8a APK is suitable for most modern Android phones.
#   The universal APK works on all architectures but is larger.
#
# Requirements:
#   - Docker (or podman aliased as docker)
#

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
IMAGE_NAME="element-x-patched"
OUTPUT_DIR="${SCRIPT_DIR}/output"

echo "==> Building Docker image (this will take 10-20 minutes)..."
docker build -t "${IMAGE_NAME}" "${SCRIPT_DIR}"

echo "==> Extracting APKs..."
mkdir -p "${OUTPUT_DIR}"

CONTAINER_ID=$(docker create "${IMAGE_NAME}")
docker cp "${CONTAINER_ID}:/home/builder/output/." "${OUTPUT_DIR}/"
docker rm "${CONTAINER_ID}" > /dev/null

echo ""
echo "==> Build complete! APKs are in ${OUTPUT_DIR}/:"
ls -lh "${OUTPUT_DIR}"/*.apk
echo ""
echo "For most Android phones, install:"
echo "  ${OUTPUT_DIR}/app-gplay-arm64-v8a-debug.apk"
