# Reproducible build of the debug APK, written the way a nixpkgs package would be.
#
# Two hard problems this file solves:
#   1. The Android SDK  -> supplied via `androidSdk` (built by androidenv in flake.nix)
#                          and exposed through ANDROID_HOME.
#   2. Gradle's network  -> `gradle` with `mitmCache` intercepts Gradle's HTTP(S)
#      dependency fetches   traffic and replays it from a hash-locked `deps.json`,
#                           so the build itself runs fully offline & reproducibly.
#
# Regenerate deps.json whenever dependencies change:
#   nix build .#default.mitmCache.updateScript && ./result
{
  lib,
  stdenv,
  gradle,
  makeWrapper,
  androidSdk,
  androidHome,
  buildToolsVersion ? "35.0.0",
}:

stdenv.mkDerivation (finalAttrs: {
  pname = "encore";
  version = "0.1.0";

  src = ./.;

  nativeBuildInputs = [
    gradle
    androidSdk
    makeWrapper
  ];

  ANDROID_HOME = androidHome;
  # Some tooling still reads the deprecated variable; set both to be safe.
  ANDROID_SDK_ROOT = androidHome;

  # Gradle downloads a prebuilt aapt2 from Maven that isn't patched for NixOS's
  # loader. Point AGP at the aapt2 that androidenv already patched instead.
  gradleFlags = [
    "-Pandroid.aapt2FromMavenOverride=${androidHome}/build-tools/${buildToolsVersion}/aapt2"
  ];

  # Build the (unsigned) debug APK. `assembleRelease` would additionally need a
  # signing keystore, which is out of scope for a hello-world.
  gradleBuildTask = "assembleDebug";

  # Run the JVM unit tests as the derivation's check phase.
  doCheck = true;
  gradleCheckTask = "testDebugUnitTest";

  mitmCache = gradle.fetchDeps {
    # `pkg` (rather than the manual's `inherit pname`) is what an out-of-tree
    # flake package must pass: the manual's shorthand resolves `pkgs.<pname>`,
    # which only exists for packages that live inside nixpkgs itself.
    pkg = finalAttrs.finalPackage;
    data = ./deps.json;
  };

  installPhase = ''
    runHook preInstall
    install -Dm644 app/build/outputs/apk/debug/app-debug.apk \
      "$out/encore.apk"
    runHook postInstall
  '';

  meta = {
    description = "Hello-world Kotlin / Jetpack Compose (Material 3) Android app";
    platforms = lib.platforms.linux;
    license = lib.licenses.mit;
  };
})
