#!/bin/bash
# Sets up the on-device agent inside DroidDeck's Linux userland: Claude Code, git and gh, loopback
# adb for droiddeckctl, and the toolchain dd-lab-build uses to build Lab builds on the device.
# Run it from the DroidDeck terminal, inside a checkout of the DroidDeck repository.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
export DEBIAN_FRONTEND=noninteractive
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT

apt-get update
apt-get install -y --no-install-recommends git gh adb python3 zip unzip curl openjdk-17-jdk-headless qemu-user zipalign apksigner

command -v claude >/dev/null || [ -x "$HOME/.local/bin/claude" ] ||
  { curl -fsSL -o "$tmp/install-claude.sh" https://claude.ai/install.sh && bash "$tmp/install-claude.sh"; }

mkdir -p "$HOME/.local/bin"
for tool in dd-agent dd-lab-build dd-gh-login android-open; do install -m755 "$here/$tool" "$HOME/.local/bin/$tool"; done
if gh auth status >/dev/null 2>&1 && ! "$here/dd-gh-login" --git; then
  echo "setup: git could not use the GitHub sign-in; run dd-gh-login --git" >&2
fi
# DroidDeck passes the live loopback adb port; a fixed one here would go stale whenever wireless debugging is toggled.
sed -i 's|ADB_SERIAL=127.0.0.1:5555 |ADB_SERIAL="${ADB_SERIAL:-127.0.0.1:5555}" |' "$HOME/.bashrc" 2>/dev/null || true
grep -q 'droiddeck-agent-path' "$HOME/.bashrc" 2>/dev/null ||
  printf '\n# droiddeck-agent-path\nexport PATH="$HOME/.local/bin:$PATH" ADB_SERIAL="${ADB_SERIAL:-127.0.0.1:5555}" BROWSER="$HOME/.local/bin/android-open"\n' >> "$HOME/.bashrc"

# Google publishes aapt2 for x86-64 Linux only; it runs here under qemu-user with Ubuntu's x86-64 runtime.
x86=$HOME/x86root
mkdir -p "$HOME/aapt2/x86" "$x86/etc"
if [ ! -x "$HOME/aapt2/x86/aapt2" ]; then
  agp=$(sed -n "s/.*com.android.tools.build:gradle:\([0-9.]*\).*/\1/p" "$here/../../build.gradle" | head -1)
  [ -n "$agp" ] || { echo "setup: no Android Gradle plugin version in build.gradle" >&2; exit 1; }
  aapt2=$(curl -fsSL "https://dl.google.com/android/maven2/com/android/tools/build/aapt2/maven-metadata.xml" |
    { grep -o "<version>$agp-[0-9]*</version>" || true; } | tail -1 | sed 's/<[^>]*>//g')
  [ -n "$aapt2" ] || { echo "setup: Google publishes no aapt2 for AGP $agp" >&2; exit 1; }
  curl -fsSL -o "$tmp/aapt2.jar" "https://dl.google.com/android/maven2/com/android/tools/build/aapt2/$aapt2/aapt2-$aapt2-linux.jar"
  unzip -o -q "$tmp/aapt2.jar" aapt2 -d "$HOME/aapt2/x86"
  chmod +x "$HOME/aapt2/x86/aapt2"
fi
if [ ! -e "$x86/lib64/ld-linux-x86-64.so.2" ]; then
  codename=$(. /etc/os-release && echo "$VERSION_CODENAME")
  curl -fsSL "https://archive.ubuntu.com/ubuntu/dists/$codename/main/binary-amd64/Packages.gz" | gunzip > "$tmp/amd64-packages"
  for package in libc6 libgcc-s1 libstdc++6 zlib1g; do
    read -r file sum < <(awk -v p="$package" '$0 == "Package: " p {found = 1} found && /^Filename:/ {f = $2}
      found && /^SHA256:/ {s = $2} found && /^$/ {exit} END {print f, s}' "$tmp/amd64-packages")
    [ -n "$sum" ] || { echo "setup: $package is not in Ubuntu $codename's amd64 index" >&2; exit 1; }
    curl -fsSL -o "$tmp/$package.deb" "https://archive.ubuntu.com/ubuntu/$file"
    echo "$sum  $tmp/$package.deb" | sha256sum -c --quiet -
    dpkg-deb -x "$tmp/$package.deb" "$x86"
  done
  ln -sfn usr/lib64 "$x86/lib64"
  ln -sfn usr/lib "$x86/lib"
  : > "$x86/etc/ld.so.preload"
fi
# AGP only accepts a custom aapt2 whose file is named aapt2.
printf '#!/bin/sh\nexec qemu-x86_64 -L %s %s/aapt2/x86/aapt2 "$@"\n' "$x86" "$HOME" > "$HOME/aapt2/aapt2"
chmod +x "$HOME/aapt2/aapt2"
"$HOME/aapt2/aapt2" version

sdk=$HOME/android-sdk
if [ ! -x "$sdk/cmdline-tools/latest/bin/sdkmanager" ]; then
  mkdir -p "$sdk/cmdline-tools"
  curl -fsSL -o "$tmp/cmdline-tools.zip" https://dl.google.com/android/repository/commandlinetools-linux-13114758_latest.zip
  unzip -q -o "$tmp/cmdline-tools.zip" -d "$sdk/cmdline-tools"
  rm -rf "$sdk/cmdline-tools/latest"
  mv "$sdk/cmdline-tools/cmdline-tools" "$sdk/cmdline-tools/latest"
fi
export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-arm64
# Ubuntu's default JDK can be newer than the Gradle wrapper supports, so every shell and Gradle run
# here uses 17, the SDK above and the qemu-wrapped aapt2, not only dd-lab-build's.
sed -i '/^# droiddeck-agent-gradle$/,+1d' "$HOME/.bashrc" 2>/dev/null || true
printf '# droiddeck-agent-gradle\nexport JAVA_HOME=%s ANDROID_HOME="$HOME/android-sdk"\n' "$JAVA_HOME" >> "$HOME/.bashrc"
mkdir -p "$HOME/.gradle"
touch "$HOME/.gradle/gradle.properties"
# Gradle's own settings carry the SDK too, for shells that do not read ~/.bashrc.
for setting in "org.gradle.java.home=$JAVA_HOME" "android.aapt2FromMavenOverride=$HOME/aapt2/aapt2" "systemProp.android.home=$sdk"; do
  sed -i "/^${setting%%=*}=/d" "$HOME/.gradle/gradle.properties"
  echo "$setting" >> "$HOME/.gradle/gradle.properties"
done
# The NDK's compilers are x86-64 only, so DroidDeck's native code is left to CI, as dd-lab-build does,
# and Conscrypt ships no aarch64 Linux library for Robolectric to load.
mkdir -p "$HOME/.gradle/init.d"
cat > "$HOME/.gradle/init.d/droiddeck-device.gradle" <<'GRADLE'
settingsEvaluated { settings ->
  if (settings.rootProject.name != 'DroidDeck') return
  gradle.startParameter.excludedTaskNames += ':app:buildVkBridgeServer'
  gradle.allprojects {
    tasks.withType(org.gradle.api.tasks.testing.Test).configureEach { systemProperty 'robolectric.conscryptMode', 'OFF' }
  }
}
GRADLE
(set +o pipefail; yes | "$sdk/cmdline-tools/latest/bin/sdkmanager" --licenses >/dev/null)
"$sdk/cmdline-tools/latest/bin/sdkmanager" "platforms;android-34" "build-tools;35.0.0" >/dev/null

adb connect 127.0.0.1:5555 || true
# The first build compiles the whole app; doing it now makes the agent's Lab builds incremental.
if [ "${DD_SKIP_PREPARE:-}" != 1 ]; then
  echo "Approve the USB debugging prompt if one appears."
  if timeout 120 adb -s 127.0.0.1:5555 wait-for-device; then
    "$here/dd-lab-build" --prepare || echo "The first Lab build will compile the whole app"
  else
    echo "adb did not connect, so the first Lab build will compile the whole app"
  fi
fi
echo "Done. Run dd-agent."
