#!/usr/bin/env bash
# Cross-compile quicprochat client for Termux (Android).
#
# Produces a statically linked, stripped aarch64 binary that runs on Termux
# without any runtime dependencies.
#
# Requires: cargo-zigbuild (preferred) or cross.
#
# Usage:
#   ./scripts/build-termux.sh              # aarch64 (default, most Android devices)
#   ./scripts/build-termux.sh x86_64       # x86_64 (emulators, Chromebooks)
#   ./scripts/build-termux.sh both         # build both architectures
#
# Output: target/<triple>/release/qpc (stripped, static)
#
# After building, copy to your phone:
#   adb push target/aarch64-unknown-linux-musl/release/qpc /sdcard/Download/
# Then in Termux:
#   cp /sdcard/Download/qpc ~/../usr/bin/ && chmod +x ~/../usr/bin/qpc
# Or run the setup script:
#   ./scripts/termux-setup.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$PROJECT_ROOT"

# ── Target selection ──────────────────────────────────────────────────────────

ARCH="${1:-aarch64}"

case "$ARCH" in
    aarch64|arm64)
        TARGETS=(aarch64-unknown-linux-musl)
        ;;
    x86_64|x86)
        TARGETS=(x86_64-unknown-linux-musl)
        ;;
    both|all)
        TARGETS=(aarch64-unknown-linux-musl x86_64-unknown-linux-musl)
        ;;
    *)
        echo "Usage: $0 [aarch64|x86_64|both]" >&2
        exit 1
        ;;
esac

# ── Size-optimised release profile ────────────────────────────────────────────

export CARGO_PROFILE_RELEASE_OPT_LEVEL=s
export CARGO_PROFILE_RELEASE_LTO=true
export CARGO_PROFILE_RELEASE_CODEGEN_UNITS=1
export CARGO_PROFILE_RELEASE_STRIP=symbols

# ── Build tool detection ──────────────────────────────────────────────────────

if command -v cargo-zigbuild &>/dev/null; then
    BUILD_CMD="cargo zigbuild"
elif command -v cross &>/dev/null; then
    BUILD_CMD="cross build"
else
    echo "ERROR: Install a cross-compilation tool:" >&2
    echo "  cargo install cargo-zigbuild   # recommended (no Docker)" >&2
    echo "  cargo install cross            # alternative (needs Docker)" >&2
    exit 1
fi

# ── Features to include ──────────────────────────────────────────────────────

# TUI is great on Termux (full terminal emulation), include it by default.
FEATURES="tui"

echo "=== quicprochat Termux build ==="
echo "Build tool: $BUILD_CMD"
echo "Targets:    ${TARGETS[*]}"
echo "Features:   $FEATURES"
echo ""

# ── Build ─────────────────────────────────────────────────────────────────────

FAILED=()
OUTPUTS=()

for target in "${TARGETS[@]}"; do
    echo "--- Building qpc for $target ---"
    if $BUILD_CMD --release --target "$target" --bin qpc --features "$FEATURES"; then
        BINARY="target/$target/release/qpc"
        if [ -f "$BINARY" ]; then
            SIZE=$(stat -c%s "$BINARY" 2>/dev/null || stat -f%z "$BINARY")
            SIZE_MB=$(echo "scale=2; $SIZE / 1048576" | bc)
            echo "  Binary: $BINARY"
            echo "  Size:   ${SIZE_MB} MB"
            OUTPUTS+=("$BINARY")
        else
            echo "  ERROR: Binary not found at $BINARY" >&2
            FAILED+=("$target (binary not found)")
        fi
    else
        echo "  ERROR: Build failed for $target" >&2
        FAILED+=("$target (build failed)")
    fi
    echo ""
done

# ── Summary ───────────────────────────────────────────────────────────────────

if [ ${#FAILED[@]} -gt 0 ]; then
    echo "=== FAILURES ==="
    for f in "${FAILED[@]}"; do
        echo "  - $f"
    done
    exit 1
fi

echo "=== Build successful ==="
echo ""
echo "Copy to your Android device:"
for out in "${OUTPUTS[@]}"; do
    echo "  adb push $out /sdcard/Download/qpc"
done
echo ""
echo "Then in Termux, run the setup script:"
echo "  curl -sSL <repo-url>/scripts/termux-setup.sh | bash"
echo "  # or copy scripts/termux-setup.sh to the device and run it"
