summaryrefslogtreecommitdiff
path: root/pkgs/development/mobile/androidenv/compose-android-packages.nix
blob: 7a92939e33fbf79bf4627c9552d99bbb5c3fca59 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
{
  callPackage,
  stdenv,
  stdenvNoCC,
  lib,
  fetchurl,
  ruby,
  writeText,
  licenseAccepted ? false,
  meta,
}:

let
  # Coerces a string to an int.
  coerceInt = val: if lib.isInt val then val else lib.toIntBase10 val;

  coerceIntVersion = v: coerceInt (lib.versions.major (toString v));

  # Parses a single version, substituting "latest" with the latest version.
  parseVersion =
    repo: key: version:
    if version == "latest" then repo.latest.${key} else version;

  # Parses a list of versions, substituting "latest" with the latest version.
  parseVersions =
    repo: key: versions:
    lib.sort (a: b: lib.strings.compareVersions (toString a) (toString b) > 0) (
      lib.unique (map (parseVersion repo key) versions)
    );
in
{
  repoJson ? ./repo.json,
  repoXmls ? null,
  repo ? (
    # Reads the repo JSON. If repoXmls is provided, will build a repo JSON into the Nix store.
    if repoXmls != null then
      let
        # Uses update.rb to create a repo spec.
        mkRepoJson =
          {
            packages ? [ ],
            images ? [ ],
            addons ? [ ],
          }:
          let
            mkRepoRuby = (
              ruby.withPackages (
                pkgs: with pkgs; [
                  slop
                  curb
                  nokogiri
                ]
              )
            );
            mkRepoRubyArguments = lib.lists.flatten [
              (map (package: [
                "--packages"
                "${package}"
              ]) packages)
              (map (image: [
                "--images"
                "${image}"
              ]) images)
              (map (addon: [
                "--addons"
                "${addon}"
              ]) addons)
            ];
          in
          stdenvNoCC.mkDerivation {
            name = "androidenv-repo-json";
            buildInputs = [ mkRepoRuby ];
            preferLocalBuild = true;
            unpackPhase = "true";
            buildPhase = ''
              env ruby -e 'load "${./update.rb}"' -- ${lib.escapeShellArgs mkRepoRubyArguments} --input /dev/null --output repo.json
            '';
            installPhase = ''
              mv repo.json $out
            '';
          };
        repoXmlSpec = {
          packages = repoXmls.packages or [ ];
          images = repoXmls.images or [ ];
          addons = repoXmls.addons or [ ];
        };
      in
      lib.importJSON "${mkRepoJson repoXmlSpec}"
    else
      lib.importJSON repoJson
  ),
  cmdLineToolsVersion ? "latest",
  toolsVersion ? "latest",
  platformToolsVersion ? "latest",
  buildToolsVersions ? [ "latest" ],
  includeEmulator ? false,
  emulatorVersion ? "latest",
  minPlatformVersion ? null,
  maxPlatformVersion ? "latest",
  numLatestPlatformVersions ? 1,
  platformVersions ?
    if minPlatformVersion != null && maxPlatformVersion != null then
      # Range between min and max, inclusive.
      let
        minPlatformVersion' = parseVersion repo "platforms" minPlatformVersion;
        maxPlatformVersion' = parseVersion repo "platforms" maxPlatformVersion;
        minPlatformVersionInt = coerceIntVersion minPlatformVersion';
        maxPlatformVersionInt = coerceIntVersion maxPlatformVersion';
        range = lib.range (lib.min minPlatformVersionInt maxPlatformVersionInt) (
          lib.max minPlatformVersionInt maxPlatformVersionInt
        );
      in
      # Don't use the actual latest version in lieu of the rounded version here,
      # since when Google upgrades it would have the nasty side effect of being
      # unstable and picking 35 -> 36 -> 37 instead of 35 -> 36.1 -> 37.
      # Best to stay consistent.
      #
      # However, if only one platform is requested and it's the latest (which is the default),
      # we should use it.
      if lib.length range == 1 then lib.singleton maxPlatformVersion' else range
    else
      # Use numLatestPlatformVersions with a lower cutoff of minPlatformVersion (defaulting to 1)
      # to determine how many of the latest *major* versions we should pick.
      let
        minPlatformVersionInt =
          if minPlatformVersion == null then
            1
          else
            coerceIntVersion (parseVersion repo "platforms" minPlatformVersion);
        latestPlatformVersionInt = lib.max minPlatformVersionInt (coerceIntVersion repo.latest.platforms);
        firstPlatformVersionInt = lib.max minPlatformVersionInt (
          latestPlatformVersionInt - (lib.max 1 numLatestPlatformVersions) + 1
        );
        range = lib.range firstPlatformVersionInt latestPlatformVersionInt;
      in
      # Ditto, see above.
      if lib.length range == 1 then lib.singleton repo.latest.platforms else range,
  includeSources ? false,
  includeSystemImages ? false,
  systemImageTypes ? [
    "google_apis"
    "google_apis_playstore"
  ],
  abiVersions ? [
    "x86"
    "x86_64"
    "armeabi-v7a"
    "arm64-v8a"
  ],
  # cmake has precompiles on x86_64 and Darwin platforms. Default to true there for compatibility.
  includeCmake ? stdenv.hostPlatform.isx86_64 || stdenv.hostPlatform.isDarwin,
  cmakeVersions ? [ "latest" ],
  includeNDK ? false,
  ndkVersion ? "latest",
  ndkVersions ? [ ndkVersion ],
  useGoogleAPIs ? false,
  useGoogleTVAddOns ? false,
  includeExtras ? [ ],
  extraLicenses ? [ ],
}:

let
  # Resolve all the platform versions.
  platformVersions' = parseVersions repo "platforms" platformVersions;

  # Determine the Android os identifier from Nix's system identifier
  os =
    {
      x86_64-linux = "linux";
      x86_64-darwin = "macosx";
      aarch64-linux = "linux";
      aarch64-darwin = "macosx";
    }
    .${stdenv.hostPlatform.system} or "all";

  # Determine the Android arch identifier from Nix's system identifier
  arch =
    {
      x86_64-linux = "x64";
      x86_64-darwin = "x64";
      aarch64-linux = "aarch64";
      aarch64-darwin = "aarch64";
    }
    .${stdenv.hostPlatform.system} or "all";

  # Converts all 'archives' keys in a repo spec to fetchurl calls.
  fetchArchives =
    attrSet:
    lib.attrsets.mapAttrsRecursive (
      path: value:
      if (builtins.elemAt path (builtins.length path - 1)) == "archives" then
        let
          validArchives = builtins.filter (
            archive:
            let
              isTargetOs =
                if builtins.hasAttr "os" archive then archive.os == os || archive.os == "all" else true;
              isTargetArch =
                if builtins.hasAttr "arch" archive then archive.arch == arch || archive.arch == "all" else true;
            in
            isTargetOs && isTargetArch
          ) value;
          packageInfo = lib.attrByPath (lib.sublist 0 (builtins.length path - 1) path) null attrSet;
        in
        lib.optionals (builtins.length validArchives > 0) (
          lib.last (
            map (
              archive:
              (fetchurl {
                pname = packageInfo.name;
                version = packageInfo.revision;
                inherit (archive) url sha1;
                inherit meta;
                passthru = {
                  info = packageInfo;
                };
              }).overrideAttrs
                (
                  finalAttrs: previousAttrs: {
                    # fetchurl prioritize `pname` and `version` over the specified `name`,
                    # so specify custom `name` in an override.
                    name = baseNameOf (lib.head (finalAttrs.urls));
                  }
                )
            ) validArchives
          )
        )
      else
        value
    ) attrSet;

  # Converts the repo attrset into fetch calls.
  allArchives = {
    packages = fetchArchives repo.packages;
    system-images = fetchArchives repo.images;
    addons = fetchArchives repo.addons;
    extras = fetchArchives repo.extras;
  };

  # Lift the archives to the package level for easy search,
  # and add recurseIntoAttrs to all of them.
  allPackages =
    let
      liftedArchives = lib.attrsets.mapAttrsRecursiveCond (value: !(builtins.hasAttr "archives" value)) (
        path: value:
        if (value.archives or null) != null && (value.archives or [ ]) != [ ] then
          lib.dontRecurseIntoAttrs value.archives
        else
          null
      ) allArchives;

      # Creates a version key from a name.
      # Converts things like 'extras;google;auto' to 'extras-google-auto'
      toVersionKey =
        name:
        let
          normalizedName = lib.replaceStrings [ ";" "." ] [ "-" "_" ] name;
          versionParts = lib.match "^([0-9][0-9\\.]*)(.*)$" normalizedName;
        in
        if versionParts == null then normalizedName else "v" + lib.concatStrings versionParts;

      recurse = lib.mapAttrs' (
        name: value:
        if builtins.isAttrs value && (value.recurseForDerivations or true) then
          lib.nameValuePair (toVersionKey name) (lib.recurseIntoAttrs (recurse value))
        else
          lib.nameValuePair (toVersionKey name) value
      );
    in
    lib.recurseIntoAttrs (recurse liftedArchives);

  # Converts a license name to a list of license texts.
  mkLicenses = licenseName: repo.licenses.${licenseName};

  # Converts a list of license names to a flattened list of license texts.
  # Just used for displaying licenses.
  mkLicenseTexts =
    licenseNames:
    lib.lists.flatten (
      map (
        licenseName: map (licenseText: "--- ${licenseName} ---\n${licenseText}") (mkLicenses licenseName)
      ) licenseNames
    );

  # Converts a license name to a list of license hashes.
  mkLicenseHashes =
    licenseName: map (licenseText: builtins.hashString "sha1" licenseText) (mkLicenses licenseName);

  # The list of all license names we're accepting. Put android-sdk-license there
  # by default.
  licenseNames = lib.lists.unique (
    [
      "android-sdk-license"
    ]
    ++ extraLicenses
  );

  # Returns true if the given version exists.
  hasVersion =
    packages: package: version:
    lib.hasAttrByPath [ package (toString version) ] packages
    || lib.hasAttrByPath [ package "${(toString version)}.0" ] packages;

  # Displays a nice error message that includes the available options if a version doesn't exist.
  # Note that allPackages can be a list of package sets, or a single package set. Pass a list if
  # you want to prioritize elements to the left (e.g. for passing a platform major version).
  checkVersion =
    allPackages: package: version:
    let
      # Convert the package sets to a list.
      allPackages' = if lib.isList allPackages then allPackages else lib.singleton allPackages;

      # Pick the first package set where we have the version.
      packageSet = lib.findFirst (packages: hasVersion packages package version) null allPackages';
    in
    if packageSet == null then
      throw ''
        The version ${toString version} is missing in package ${package}.
        The only available versions are ${
          lib.concatStringsSep ", " (
            lib.attrNames (lib.foldl (s: x: s // (x.${package} or { })) { } allPackages')
          )
        }.
      ''
    else
      packageSet.${package}.${toString version} or packageSet.${package}."${toString version}.0";

  # Returns true if we should link the specified plugins.
  shouldLink =
    check: packages:
    assert builtins.isList packages;
    if check == true then
      true
    else if check == false then
      false
    else if check == "if-supported" then
      let
        hasSrc =
          package: package.src != null && (builtins.isList package.src -> builtins.length package.src > 0);
      in
      packages != [ ] && lib.all hasSrc packages
    else
      throw "Invalid argument ${toString check}; use true, false, or if-supported";

  # Function that automatically links all plugins for which multiple versions can coexist
  linkPlugins =
    {
      name,
      plugins,
      check ? true,
    }:
    lib.optionalString (shouldLink check plugins) ''
      mkdir -p ${name}
      ${lib.concatMapStrings (plugin: ''
        ln -s ${plugin}/libexec/android-sdk/${name}/* ${name}
      '') plugins}
    '';

  # Function that automatically links all NDK plugins.
  linkNdkPlugins =
    {
      name,
      plugins,
      rootName ? name,
      check ? true,
    }:
    lib.optionalString (shouldLink check plugins) ''
      mkdir -p ${rootName}
      ${lib.concatMapStrings (plugin: ''
        ln -s ${plugin}/libexec/android-sdk/${name} ${rootName}/${plugin.version}
      '') plugins}
    '';

  # Function that automatically links the default NDK plugin.
  linkNdkPlugin =
    {
      name,
      plugin,
      check,
    }:
    lib.optionalString (shouldLink check [ plugin ]) ''
      ln -s ${plugin}/libexec/android-sdk/${name} ${name}
    '';

  # Function that automatically links a plugin for which only one version exists
  linkPlugin =
    {
      name,
      plugin,
      check ? true,
    }:
    lib.optionalString (shouldLink check [ plugin ]) ''
      ln -s ${plugin}/libexec/android-sdk/${name} ${name}
    '';

  linkSystemImages =
    { images, check }:
    lib.optionalString (shouldLink check images) ''
      mkdir -p system-images
      ${lib.concatMapStrings (system-image: ''
        apiVersion=$(basename $(echo ${system-image}/libexec/android-sdk/system-images/*))
        type=$(basename $(echo ${system-image}/libexec/android-sdk/system-images/*/*))
        mkdir -p system-images/$apiVersion
        ln -s ${system-image}/libexec/android-sdk/system-images/$apiVersion/$type system-images/$apiVersion/$type
      '') images}
    '';

  # Links all plugins related to a requested platform
  linkPlatformPlugins =
    {
      name,
      plugins,
      check,
    }:
    lib.optionalString (shouldLink check plugins) ''
      mkdir -p ${name}
      ${lib.concatMapStrings (plugin: ''
        ln -s ${plugin}/libexec/android-sdk/${name}/* ${name}
      '') plugins}
    ''; # */

in
lib.recurseIntoAttrs rec {
  deployAndroidPackages = callPackage ./deploy-androidpackages.nix {
    inherit
      stdenv
      lib
      mkLicenses
      meta
      os
      arch
      ;
  };

  deployAndroidPackage = (
    {
      package,
      buildInputs ? [ ],
      patchInstructions ? "",
      meta ? { },
      ...
    }@args:
    let
      extraParams = removeAttrs args [
        "package"
        "os"
        "arch"
        "buildInputs"
        "patchInstructions"
      ];
    in
    deployAndroidPackages (
      {
        inherit buildInputs;
        packages = [ package ];
        patchesInstructions = {
          "${package.name}" = patchInstructions;
        };
      }
      // extraParams
    )
  );

  all = allPackages;

  platform-tools = callPackage ./platform-tools.nix {
    inherit
      deployAndroidPackage
      os
      arch
      meta
      ;
    package = checkVersion allArchives.packages "platform-tools" (
      parseVersion repo "platform-tools" platformToolsVersion
    );
  };

  tools = callPackage ./tools.nix {
    inherit
      deployAndroidPackage
      os
      arch
      meta
      ;
    package = checkVersion allArchives.packages "tools" (parseVersion repo "tools" toolsVersion);

    postInstall = ''
      ${linkPlugin {
        name = "platform-tools";
        plugin = platform-tools;
      }}
      ${linkPlugin {
        name = "emulator";
        plugin = emulator;
        check = includeEmulator;
      }}
    '';
  };

  build-tools = map (
    version:
    callPackage ./build-tools.nix {
      inherit
        deployAndroidPackage
        os
        arch
        meta
        ;
      package = checkVersion allArchives.packages "build-tools" version;

      postInstall = ''
        ${linkPlugin {
          name = "tools";
          plugin = tools;
          check = toolsVersion != null;
        }}
      '';
    }
  ) (parseVersions repo "build-tools" buildToolsVersions);

  emulator = callPackage ./emulator.nix {
    inherit
      deployAndroidPackage
      os
      arch
      meta
      ;
    package = checkVersion allArchives.packages "emulator" (
      parseVersion repo "emulator" emulatorVersion
    );

    postInstall = ''
      ${linkSystemImages {
        images = system-images;
        check = includeSystemImages;
      }}
    '';
  };

  # This is a list of the chosen API levels, as integers.
  platformVersions = platformVersions';

  platforms = map (
    version:
    deployAndroidPackage {
      package = checkVersion allArchives.packages "platforms" version;
    }
  ) platformVersions';

  # Google is not including sources for API 37+. If the user requests them, don't fail.
  sources = lib.filter (source: source != null) (
    map (
      version:
      let
        package =
          let
            version' = builtins.tryEval (checkVersion allArchives.packages "sources" version);
          in
          if version'.success then version'.value else null;
      in
      if package == null then
        null
      else
        deployAndroidPackage {
          inherit package;
        }
    ) platformVersions'
  );

  system-images = lib.flatten (
    map (
      apiVersion:
      map (
        type:
        # Deploy all system images with the same  systemImageType in one derivation to avoid the `null` problem below
        # with avdmanager when trying to create an avd!
        #
        # ```
        # $ yes "" | avdmanager create avd --force --name testAVD --package 'system-images;android-33;google_apis;x86_64'
        # Error: Package path is not valid. Valid system image paths are:
        # null
        # ```
        let
          availablePackages =
            map (abiVersion: allArchives.system-images.${toString apiVersion}.${type}.${abiVersion})
              (
                builtins.filter (
                  abiVersion: lib.hasAttrByPath [ (toString apiVersion) type abiVersion ] allArchives.system-images
                ) abiVersions
              );

          instructions = lib.listToAttrs (
            map (package: {
              name = package.name;
              value = lib.optionalString (lib.hasPrefix "google_apis" type) ''
                # Patch 'google_apis' system images so they're recognized by the sdk.
                # Without this, `android list targets` shows 'Tag/ABIs : no ABIs' instead
                # of 'Tag/ABIs : google_apis*/*' and the emulator fails with an ABI-related error.
                sed -i '/^Addon.Vendor/d' source.properties
              '';
            }) availablePackages
          );
        in
        lib.optionals (availablePackages != [ ]) (deployAndroidPackages {
          packages = availablePackages;
          patchesInstructions = instructions;
        })
      ) systemImageTypes
    ) platformVersions'
  );

  cmake = map (
    version:
    callPackage ./cmake.nix {
      inherit
        deployAndroidPackage
        os
        arch
        meta
        ;
      package = checkVersion allArchives.packages "cmake" version;
    }
  ) (parseVersions repo "cmake" cmakeVersions);

  # All NDK bundles.
  ndk-bundles =
    let
      # Creates a NDK bundle.
      makeNdkBundle =
        package:
        callPackage ./ndk-bundle {
          inherit
            deployAndroidPackage
            os
            arch
            platform-tools
            meta
            package
            ;
        };
    in
    lib.flatten (
      map (
        version:
        let
          package = makeNdkBundle (
            allArchives.packages.ndk-bundle.${version} or allArchives.packages.ndk.${version}
          );
        in
        lib.optional (shouldLink includeNDK [ package ]) package
      ) (parseVersions repo "ndk" ndkVersions)
    );

  # The "default" NDK bundle.
  ndk-bundle = if ndk-bundles == [ ] then null else lib.head ndk-bundles;

  # Makes a Google API bundle from supported versions.
  google-apis = map (
    version:
    deployAndroidPackage {
      package = (checkVersion allArchives "addons" version).google_apis;
    }
  ) (lib.filter (hasVersion allArchives "addons") platformVersions');

  # Makes a Google TV addons bundle from supported versions.
  google-tv-addons = map (
    version:
    deployAndroidPackage {
      package = (checkVersion allArchives "addons" version).google_tv_addon;
    }
  ) (lib.filter (hasVersion allArchives "addons") platformVersions');

  cmdline-tools-package = checkVersion allArchives.packages "cmdline-tools" (
    parseVersion repo "cmdline-tools" cmdLineToolsVersion
  );

  # This derivation deploys the tools package and symlinks all the desired
  # plugins that we want to use. If the license isn't accepted, prints all the licenses
  # requested and throws.
  androidsdk = callPackage ./cmdline-tools.nix {
    inherit
      deployAndroidPackage
      os
      arch
      meta
      ;

    package = cmdline-tools-package;

    postInstall =
      if !licenseAccepted then
        throw ''
          ${builtins.concatStringsSep "\n\n" (mkLicenseTexts licenseNames)}

          You must accept the following licenses:
          ${lib.concatMapStringsSep "\n" (str: "  - ${str}") licenseNames}

          a)
            by setting nixpkgs config option 'android_sdk.accept_license = true;'.
          b)
            by an environment variable for a single invocation of the nix tools.
              $ export NIXPKGS_ACCEPT_ANDROID_SDK_LICENSE=1
        ''
      else
        ''
          # Symlink all requested plugins
          ${linkPlugin {
            name = "platform-tools";
            plugin = platform-tools;
          }}
          ${linkPlugin {
            name = "tools";
            plugin = tools;
            check = toolsVersion != null;
          }}
          ${linkPlugins {
            name = "build-tools";
            plugins = build-tools;
          }}
          ${linkPlugin {
            name = "emulator";
            plugin = emulator;
            check = includeEmulator;
          }}
          ${linkPlugins {
            name = "platforms";
            plugins = platforms;
          }}
          ${linkPlatformPlugins {
            name = "sources";
            plugins = sources;
            check = includeSources;
          }}
          ${linkPlugins {
            name = "cmake";
            plugins = cmake;
            check = includeCmake;
          }}
          ${linkNdkPlugins {
            name = "ndk-bundle";
            rootName = "ndk";
            plugins = ndk-bundles;
            check = includeNDK;
          }}
          ${linkNdkPlugin {
            name = "ndk-bundle";
            plugin = ndk-bundle;
            check = includeNDK;
          }}
          ${linkSystemImages {
            images = system-images;
            check = includeSystemImages;
          }}
          ${linkPlatformPlugins {
            name = "add-ons";
            plugins = google-apis;
            check = useGoogleAPIs;
          }}
          ${linkPlatformPlugins {
            name = "add-ons";
            plugins = google-tv-addons;
            check = useGoogleTVAddOns;
          }}

          # Link extras
          ${lib.concatMapStrings (
            identifier:
            let
              package = allArchives.extras.${identifier};
              path = package.path;
              extras = callPackage ./extras.nix {
                inherit
                  deployAndroidPackage
                  package
                  os
                  arch
                  meta
                  ;
              };
            in
            ''
              targetDir=$(dirname ${path})
              mkdir -p $targetDir
              ln -s ${extras}/libexec/android-sdk/${path} $targetDir
            ''
          ) includeExtras}

          # Expose common executables in bin/
          mkdir -p $out/bin

          for i in ${platform-tools}/bin/*; do
              ln -s $i $out/bin
          done

          ${lib.optionalString (shouldLink includeEmulator [ emulator ]) ''
            for i in ${emulator}/bin/*; do
                ln -s $i $out/bin
            done
          ''}

          find "$ANDROID_HOME/${cmdline-tools-package.path}/bin" -type f -executable | while read i; do
              ln -s $i $out/bin
          done

          # Write licenses
          mkdir -p licenses
          ${lib.concatMapStrings (
            licenseName:
            let
              licenseHashes = builtins.concatStringsSep "\n" (mkLicenseHashes licenseName);
              licenseHashFile = writeText "androidenv-${licenseName}" licenseHashes;
            in
            ''
              ln -s ${licenseHashFile} licenses/${licenseName}
            ''
          ) licenseNames}
        '';
  };
}